Gaurav Aggarwal Gaurav Aggarwal - 4 months ago 10
jQuery Question

Different behaviour of javascript and jquery

I have a button and I am changing its value and name on click showing same value in alert. Its working fine when I use jQuery but not when I use call function with JavaScript function value is not changing in front view but in alert value is changing its totally strange.

Here are the demos

JavaScript



function change() {
if ($(this).attr('name') == 'first') {
$(this).attr('name', 'second');
$(this).attr('value', 'second');
alert('new name ' + $(this).attr('name'));
} else {
$(this).attr('name', 'first');
$(this).attr('value', 'first');
alert('new name ' + $(this).attr('name'));
}
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" id="button" value="first" name="first" onclick="change()">





jQuery



$('#button').click(function() {
if ($(this).attr('name') == 'first') {
$(this).attr('name', 'second');
$(this).attr('value', 'second');
alert('new name ' + $(this).attr('name'));
} else {
$(this).attr('name', 'first');
$(this).attr('value', 'first');
alert('new name ' + $(this).attr('name'));
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" id="button" value="first" name="first">





I know I can use jQuery as I am already including the library but I so much wanted to know what is the difference between these two.

Answer

You need to pass this to change function so that you can access the clicked object inside that function, .click() event of any element will automatically detect $(this) but in function you need to pass it

Pass this in change() function in button:

<input type="submit" id="button" value="first" name="first"  onclick="change(this)">

So change function will have:

function change(obj) {
  if ($(obj).attr('name') == 'first') {
    $(obj).attr('name', 'second');
    $(obj).attr('value', 'second');
    alert('new name ' + $(obj).attr('name'));
  } else {
    $(obj).attr('name', 'first');
    $(obj).attr('value', 'first');
    alert('new name ' + $(obj).attr('name'));
  }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" id="button" value="first" name="first"  onclick="change(this)">