Reputation: 16649
I need to 'click' one button using JavaScript, when the user clicks another button.
In Chrome on Mac, the following works fine. However, in Safari on Mac, clicking the button simply reloads the current page, rather than triggering the expected behaviour.
JS
$( 'document' ).ready( function() {
var $myForm = $('#my-form');
$('#button-fake').on('click', function(){
console.log("FAKE CLICKED");
if ($myForm[0].checkValidity()){
console.log("FORM VALID");
$('#button-real').click();
console.log("FORM SUBMITTED");
}
});
});
HTML
<input type="submit" id="button-fake" value="Fake button" />
<input type="submit" id="button-real" value="Real button" />
PS: Not my idea, I just need to get it working.
Upvotes: 0
Views: 80
Reputation: 50291
You may need to add e.preventDefault();
var $myForm = $('#my-form');
$('#button-fake').on('click', function(e) {
e.preventDefault();
console.log("FAKE CLICKED");
if ($myForm[0].checkValidity()) {
console.log("FORM VALID");
$('#button-real').click();
console.log("FORM SUBMITTED");
}
});
$('#button-real').on('click', function(e) {
console.log('button-real clicked')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='my-form'>
<input type='text' required>
<button type='submit' id='button-fake'>Submit</button>
<button type='button' id='button-real'>Real</button>
</form>
Upvotes: 2
Reputation: 4534
The button will trigger a form submit. The form submit will reload the page. To prevent this, call preventDefault().
$( 'document' ).ready( function() {
var $myForm = $('#my-form');
$('#button-fake').on('click', function(e){
e.preventDefault(); // <- This
console.log("FAKE CLICKED");
if ($myForm[0].checkValidity()){
console.log("FORM VALID");
$('#button-real').click();
console.log("FORM SUBMITTED");
}
});
});
Upvotes: 1