0

I have a table of records where each row has got a save button. would someone please help me to get the id of the button and values of two inputs on button click

<input class="price" name="price" id="price_<?= $value['i_id'] ?>" value="<?= &cost ?>" />                         
<input type="hidden" id="<?= $value['i_id'] ?>_suffix" value="<?= $value['suffix'] ?>" /> 
<button type="button" class="sp-save btn btn-xs btn-primary btn-bell m-l-xs" id="save_<?= $value['i_id'] ?>">SAVE</button> 

jquery

 save_id = $(this).attr(\'id\'); 
          id = save_id.replace( /save_/, \' \' ); //this is id of the button
price = $(\'#\'+\'price_\'+id).val(); // values comes undefined         

s_id = $(\'#\'+id+\'_suffix\').val();  //values comes undefined
2
  • Simpler to just use classes and look for each class within the specific row Commented Aug 17, 2020 at 23:34
  • just use a data attribute Commented Aug 17, 2020 at 23:43

1 Answer 1

1

It's a good idea to use a data attribute to set and retrieve id on button click. Below, I added a data attribute to the button and used jQuery's data() to get the id on click.

<input class="price" name="price" id="price_<?= $value['i_id'] ?>" value="<?= &cost ?>" />                         
<input type="hidden" id="<?= $value['i_id'] ?>_suffix" value="<?= $value['suffix'] ?>" /> 
<button type="button" class="sp-save btn btn-xs btn-primary btn-bell m-l-xs" id="save_<?= $value['i_id'] ?>" data-id="<?= $value['i_id'] ?>">SAVE</button>

jQuery:

id = $(this).data('id');       
price = $('#'+'price_'+id).val();         
s_id = $('#'+id+'_suffix').val();  
Sign up to request clarification or add additional context in comments.

2 Comments

A little explanation might be helpful. What was the problem and how does your code solve it?
It's good idea to use data attribute to set id and retrieve id on button click. So In above code I have added data attribute to button. In jQuery: I have used this data attribute to get id on click

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.