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.
nameof input. General thumb rule.val("value")instead ofattr("value","value")