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

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

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");

$btn = $('input[type="submit"]'); will select all the submit input elements in the DOM (so you are basically binding this event handler to both of your submit buttons when you call $btn.click(...).
Since you have IDs on each of your buttons you can change:
$btn = $('input[type="submit"]');
To:
$btn = $('#show_hint');
You can also find a root element to start your selector so that you are only selecting the button you want:
$btn = $('#ancestor-element').find('input[type="submit"]');
Or if you want to select all input[type="submit"] elements except the one in the form:
$btn = $('input[type="submit"]').not($('#form').find('input[type="submit"]'));

Change the button type to normal input button instead of submit. Change your script to bind your buttons to functions by selecting ID selector
In the below code $("#show_hint") will return an object of the input button with an id show_hint.
// Button 1
HTML
<input id="show_hint" class="button" type="button" value="Hint" onClick="location.href='#hint'" />
Script
$(function(){
var count = 3,
$("#show_hint").val($(this).val()+' ('+count+')')
$("#show_hint").click(function(){
$("#show_hint").val($(this).val().replace(count,count-1));
count--
// Your remaining code...
For the second button
HTML
<input id="showmenu_win2" class="button" type="input" value="Menu" />
Script
$('#showmenu_win2').click(function() {
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "insert.php"
});
return false;
});

You could replace the <input type="submit"> by a regular <button>. do achieve the same goal.
You could even create a <div> with an onclick event to mimic a button. You are not limited to input type="submit"

I am not sure this is the solution you want.My answer is to set show/hide button to type="button" while submit is type="submit".
Example
<button id="hide" type="button" >Hide</button>
<button id="show" type="button" >Show</button>

Related

multiple submit buttons only first initializes javascript

I'm echoing the Submit Button as seen below in each row of a Table. When clicked the Submit Button the Javascript initializes and alert()'s the response. The issue is only the first Button works as intended and subsequent buttons redirect to foobar.php.
Submit Button:
<form name="savefilenote" id="savefilenote" method="post" action="forbidden-savefilenote.php?notetype=2">Note: <input id="filenote" name="filenote" type="text" value="'.$filenote.'"> <input id="filename" name="filename" type="hidden" value="'.$filename.'"> <input type="submit" value="Save"></form>
Javascript:
<script>
$(function(){
$('.savefilenote').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize
beforeSend: function(){
$('#result').html('');
},
success: function(data){
$('#result').html(data);
if(data === "0") {
alert("foo");
}
if(data === "1") {
alert("bar");
}
}
});
});
});
</script>
Use a class instead of an id.
$("#savefilenote") can find only one instance of a button since and ID works for a specific element. If you change it to $(".savefilenote") and apply the same class to all buttons it should work.
id should be specific to a single element. Using the same id to identify multiple tags, you'll end up only affecting the first element in the body. If you want to associate a behavior to a group of elements, you'll need to use a class.

changin form ID and using button submit event firing old submit ID

I have apiece of code where i am changing the ID of the form
like this;
$("form").prop('id','FormApplied');
before the above formID was Form1
i have two functions
$(document).on('submit','#FormApplied',function(e) {
$(document).on('submit','#Form1',function(e) {
it is always firing the Form1, even i had changed the formID, how can i fix that because both functions have separate logic written
Thanks
When you apply an event listener to a form element, the event doesn't know about what selector was used (In this case you are selecting the element by ID.)
There are several choices.
You could use one event handler and then use that to decide which logic to use, but that has the bad effect of mixing logic (what to do when the button is pressed) with presentation logic (the ID of the button).
You could set a data-* property on the element and select off that, but think even that is a bit more awkward.
Instead, I would use two buttons, and just toggle the visibility based upon the rules
function showButton(butNumber) {
document.getElementById("but1").style.display = "none";
document.getElementById("but2").style.display = "none";
document.getElementById("but" + butNumber).style.display = "";
}
showButton(1);
document.getElementById("but1").addEventListener("click", function() {
console.log("Button 1");
showButton(2);
});
document.getElementById("but2").addEventListener("click", function() {
console.log("Button 2");
showButton(1);
});
<form>
<button type="button" id="but1">Button 1</button>
<button type="button" id="but2">Button 2</button>
</form>
It doesn't trigger both functions
function changeValue(){
$('#formId').prop('id', 'formId2');
console.log('form Id changed');
}
$(document).on('submit','#formId',function(e) {
console.log('submitted');
});
$(document).on('submit','#formId2',function(e) {
console.log('submitted 2');
});
function restoreId(){
$('#formId2').prop('id', 'formId');
console.log('form Id restored');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='formId'>
<input type='hidden' value=0 id='hiddenInput'/>
<input type='button' value='click to change the id ' onclick='changeValue()'/>
<input type='button' value='click to restore the id ' onclick='restoreId()'/>
<input type='submit' value='submit' />
</form>

find the button that submitted the form

I have this javascript:
$('#new_campaign_update').on('submit', function(event) {
debugger;
});
Is there a way I can find the button that submitted the form?
<%= form.submit 'Publish', class: 'button button-large button-primary accent-black', title: 'Publish this update now' %>
That is the button I clicked in order to submit the form can I find it on the event or something?
Yes you can with the event's currentTarget:
const buttons = document.querySelectorAll('input');
buttons.forEach(b => b.addEventListener('click', (e) => {
console.log(e.currentTarget);
e.currentTarget.style = "background-color:blue;";
}));
<input type="submit" id="a">
<input type="submit" id="b">
<input type="submit" id="c">
<input type="submit" id="d">
Assuming you have a form with id=new_campaign_update, and inside you have a single button with a class button-primary, the button will be accessible by $(this).find(".button-primary"), so you will access it like this:
$('#new_campaign_update').on('submit', function(event) {
const $button = $(this).find(".button-primary");
});
$(this) inside jQuery callbacks refers to the element that fired the callback. Inside the element you find the button with .find(".button-primary)"
Alternatively, if you have many buttons in a single form, you can add an onclick handler to the buttons themselves like this:
$('#new_campaign_update .button-primary').click(function() {
const $button = $(this);
}

onClick and action html

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>
Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href
You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});
You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>
Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

Javascript have to click button twice which is outside the form

Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.

Categories

Resources