Maurice Maurice - 15 days ago 5
Javascript Question

Button is overriding/conflicting with another button on the same webpage

I have 2 buttons on my page. Button 1 is executing a javascript function and another one is used for form processing. The problem is that button 1 is overriding the value and function of button 2.

Button 1 (not in a form) has the following html code:

<input id="show_hint" class="button" type="submit" value="Hint" onClick="location.href='#hint'" />


The javascript attached to it is:

// Button 1
$(function(){
var count = 3,
$btn = $('input[type="submit"]');
$btn.val($btn.val()+' ('+count+')')

$btn.click(function(){
$btn.val($btn.val().replace(count,count-1));
count--;
$('#hintscore')
.hide()
.css({
bottom: 30,
left: 300,
opacity: 1,
})
.show()
.stop()
.delay(200)
.animate({'bottom':75, opacity: 0},1000);

if(count==0) {
return !$btn.attr('disabled','disabled');
}
})
});


Button 2 (in a form) has this html code:

<input id="showmenu_win2" class="button" type="submit" value="Menu" />


The javascript attached to it is:

$('#form').submit(function() {
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "insert.php"
});
return false;
});


So these two are conflicting with each other and it has something to do with the type="submit". But how can I fix this?

Many thanks

Answer

This part of your JS:

$btn = $('input[type="submit"]'); 

is selecting both buttons and thus will attach the same behavior to both buttons.

Since you have an id on each button, you can select exactly the button you want by id:

$btn = $("#show_hint");