1

I am a newbie in drupal. I created a form that perform ajax action. How can I change the button name after click by using ajax.

function auktion_fav_form($form, &$form_state, $auktion_id) { 
  form['add_to_fav'] = array(
    '#type' => 'submit',
    '#id' => 'submit',
    '#value' => t($value),
    '#ajax' => array(
      'callback' => 'auktion_fav_submit',
      'wrapper' => 'submit',
      'method' => 'replace',
      'effect' => 'fade',
    )
  );
  return $form;
}
function auktion_fav_form_submit($form, &$form_state) {
  $form['add_to_fav']['#value'] = "remove from favourite;
  return $form['add_to_fav'];
}

4 Answers 4

3

In hook form alter define your submit value . Below is small piece of code .

   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
     '#prefix' => '<div id="div-example">',
     '#suffix' => '</div>',
    '#ajax' => array(
        'callback' => 'example_ajax_form_callback',
        'wrapper' => 'div-example',
         'method' => 'replace',
      ),
     );

function example_ajax_form_callback($form, &$form_state) {
  $form['submit']['#value'] = 'New value';
    return $form['submit']; 
  }
7
  • Form button does not change to new Value. But the response contain new value May 6, 2016 at 10:54
  • i tried the whole code as it is and posted it .. I wander y it not changing..are you doing something in form alter or is it a new form May 6, 2016 at 11:22
  • its a new form.. and I got the new content as #value, but not changed the value of the button dynamically. If I refresh the page it will show the changes.. May 6, 2016 at 11:33
  • are you doing this '#value' => t($value), if yes where is $value defined in your form ?? May 6, 2016 at 11:41
  • yes..$value is conditionally filled value.. if in value in my database then $value = "Remove from favourite" else $value = "Add to favourite" May 6, 2016 at 11:49
1

you can use hook_form_alter

 yourmodule_form_alter{

   $form_state['values']['add_to_fav'] = "remove from favourite";        

}
0
0

You can do it by changing your code to

function auktion_fav_form_submit($form, &$form_state) {
  $form_state['add_to_fav']['#value'] = "remove from favourite";
  return $form['add_to_fav'];
}
0

Add this code in your themes js file:

jQuery(document).ready(function(){
  jQuery("#submit").click(function(){ 
    switch (jQuery(this).val()) {
      case 'Your-button-text-here':       **//this is the text of the button which you want to change now change it with your button name**

        jQuery('#submit').val('remove from favourite');
        break;
    };
  });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.