Reputation: 10187
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.
Upvotes: 0
Views: 56
Reputation: 8101
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)">
Upvotes: 4
Reputation: 122
passing 'this' to the function and using it instead of 'this' inside the function solves your problem.
because using 'this' inside a function not handled by Jquery event, returns the owner of the function that is an object of the button you have while in jquery it returns a jQuery object
function change(btn){
if($(btn).attr('name') == 'first'){
$(btn).attr('name','second');
$(btn).attr('value','second');
alert('new name '+$(btn).attr('name'));
} else {
$(btn).attr('name','first');
$(btn).attr('value','first');
alert('new name '+$(btn).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)">
Upvotes: 0