0

I have an ajax search that returns values like this:

<a id="searchmykad" href="#" onclick="updatemykad(123123);return false;">Person a</a>
<a id="searchmykad" href="#" onclick="updatemykad(1231236);return false;">Person b</a>

And the javascript function looks like this:

  <script>
  function updatemykad(mykad) {
    $('#searchmykad').click(function(){
    $('#asd').val(mykad);
                              } 
  )}
  </script>

Its updating this textbox:

<input type="text" id="asd" name="asd" value="" class="form-control" autocomplete="off" placeholder="Search Name..." class="input-block-level" placeholder="Search Mykad..." maxlength="12" style="width:100%; " />

Now for all extensive purposes this works. I can select the first result and the value will go into the textbox, however cause all the id's are the same. I can only do it with one. (At least that is what I am thinking).

Can anyone help me get this so all the values will go into the textbox on click.

Best regards Johan Fourie

1
  • Cannot have more than one of the same HTML id attribute on a page. Commented Nov 25, 2015 at 1:06

2 Answers 2

1

You shouldn't use duplicate IDs in your elements.

Try this in your Javascript:

  <script>
  function updatemykad(mykad) {
    $('#asd').val(mykad);
  )}
  </script>
Sign up to request clarification or add additional context in comments.

3 Comments

But what tells it that this must be onclick now?
Your HTML does! The onclick attribute executes the javascript that follows it. Your javascript is updatemykad, and that's what's being executed when you click the button.
Thank you, I appreciate it!
0

As mentioned by others, HTML ID's should not be repeated, instead use class. IMHO, you could improve the overall HTML and JS code if you keep them separate. There are many ways you can go about it, something like this will be easier to maintain (just a suggestion):

// Target all the buttons with class .searchmykad with a click event listener.
// Get the values and target input ID from the HTML data attributes.
$('.searchmykad').click(function() {
  $('#' + this.dataset.target).val(this.dataset.val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="searchmykad" href="#" data-val="123123" data-target="asd">Person a</a>
<a class="searchmykad" href="#" data-val="1231236" data-target="asd">Person b</a>
<input type="text" id="asd" name="asd" value="" class="form-control" autocomplete="off" placeholder="Search Name..." class="input-block-level" placeholder="Search Mykad..." maxlength="12" style="width:100%; " />

Comments

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.