0

i have a input field and a submission button like so

<label for="name" class="col-sm-2 col-form-label">name</label>
<input type="text" class="form-control" id="name" data-belongsto="<?php echo  $id; ?>" value="<?php echo $name; ?>">

<button type="button" class="update_record btn btn-primary mb-3 mt-2" id="<?php $id; ?>">Update</button>

and i have the script like so

/*Document Ready */
$(document).ready(function () {

    $(document).on('click', '.update_record', function() {
        let btnId= $(this).attr("id");
        let name = //store name value if id == "name" and data-belongsto == btnId
    });

});

what i want to do is to get the name value out and store it in a variable if id == "name" and data-belongsto == btnId

biberman
  • 5,606
  • 4
  • 11
  • 35
6563cc10d2
  • 193
  • 1
  • 2
  • 8
  • 1
    Does this answer your question? [How to get the data-id attribute?](https://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute) – Justinas Jul 01 '21 at 11:22
  • it kinda does but is there a one liner solution to this like if i do the above i would need to compare after geting the value in if – 6563cc10d2 Jul 01 '21 at 11:26
  • 1
    You mean like `let name = $(this).attr('id') == 'name' && $(this).data('belongsto') == btnId ? $(this).val() : null`? – Justinas Jul 01 '21 at 11:33

1 Answers1

1

Firstly you should avoid using "name" as id for any element because name is an attribute that is used for various HTML input elements which may cause issues as inputs inside a form can be addressed using their name attribute, hence I used 'nm' instead of 'name'.

And if I understood correctly, this is how you can get the desired value:

$(document).on('click', '.update_record', function() {
   let btnId= $(this).attr("id");

   // get the element via css selector using jquery and store its value
   let name = $(`input#nm[data-belongsto=${btnId}]`).val();
});
ahmedazhar05
  • 580
  • 4
  • 7