Identifying specific button in a form - javascript

so I want to get a specific value if a button is clicked in my form, but somehow its listening on all buttons and not only the buttons in my form.
Instead of the javascript example below I also tried calling the class by
$('.modifygap').bind('click', function (e) {
but in this example the value didnt get set correctly.
Here is my html:
<button type="button" id="anotherbutton">Another</button>
<form action="editortoken_information" id="showtoken" method="POST">
<button class="btn btn-outline-secondary" type="submit" name="modifygap" id="modifygap" class="modifygap"
value="14" data-value="test">14</button>
<button class="btn btn-outline-secondary" type="submit" name="modifygap" id="modifygap" class="modifygap"
value="15" data-value="test">15</button>
</form>
And here is my javascript function:
$(document.getElementById("showtoken")).ready(function () {
$("button").click(function (e) {
e.preventDefault();
document.getElementById('tokenindex').value = this.getAttribute("data-value");
})
})
I thought by listening only on the specific id it would only detect button clicks in the form. But for some reason it is listening to all button clicks.

Use event.target.value to get the value of clicked element.
$(document).ready(() => {
$('.modifygap').bind('click', function (e) {
console.log('e', e.target.getAttribute("data-value"))
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="anotherbutton">Another</button>
<button class="btn btn-outline-secondary modifygap" type="submit" name="modifygap" id="modifygap"
value="14" data-value="test14">14</button>
<button class="btn btn-outline-secondary modifygap" type="submit" name="modifygap" id="modifygap"
value="15" data-value="test15">15</button>

Related

confirm cancel button not stopping JavaScript

I have a script that trigger when the submit button is clicked.
It has a return confirm javascript. If the user clicks OK, it works fine, but if they click CANCEL, it still triggers by rolling the spinner continuously.
Please help.
Below is the code snippet:
<script>
//submit search, display loading message
$('#searchbtn').click(function () {
$('.spinner').css('display', 'block');
});
</script>
<input type="submit" value="Search" id="searchbtn" class="btn btn-primary btn-block" onclick=" return confirm('Are you sure to proceed')" />
The below is the HTML for those asking.
<p>
#using (Html.BeginForm("AllLoanProcessed", "Transactions", new { area = "Transactions" }, FormMethod.Get , new { id = "formID" }))
{
<b>Search By:</b>
#Html.RadioButton("searchBy", "Account_Number", true) <text>Account Number</text>
#Html.RadioButton("searchBy", "Surname") <text> Surname </text> <br />
#Html.TextBox("search", null, new { placeholder = "Search Value", #class = "form-control" })
<br />
<input type="submit" value="Search" id="searchbtn" class="btn btn-primary btn-block" />
}
</p>
you can write your code like this too, instead of calling click event 2 times you can call it at once, try my below code, this may help you.
$('#searchbtn').click(function () {
var x = confirm("Are you sure to proceed"); //confirm text
if (x == true) { //checking wheather user clicked ok or cancel
$( "form" ).submit();
$('.spinner').css('display', 'block'); //if clicked ok spinner shown
} else { //else if clicked cancel spinner is hidden
$('.spinner').css('display', 'none');
return false //stops further process
}
})
.spinner{
display:none;
}
<form action="javascript:alert( 'success!' );">
<input type="text"/>
<input type="button" value="Search" id="searchbtn" class="btn btn-primary btn-block" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h1 class="spinner">
my spinner
</h1>
change h1 of the spinner to your spinner,
try it here fiddle
you need to put more code, this is not enough, but I guess this may help you:
$('#searchbtn').click(function () {
$('.spinner').show();
//start code to search
setInterval(function() {
//finish code to search
$('.spinner').hide();
}, 5000);
});
$('#cancelbtn').click(function () {
$('.spinner').hide();
});
.spinner{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="spinner"> This is a spinner</div>
<button type="button" class="btn btn-danger btn-block" id="cancelbtn">Cancel</button>
<button type="button" class="btn btn-primary btn-block" id="searchbtn">Search</button>
if you're using bootstrap (I assume this by the class btn btn-danger) the best practice is using an button element. And you can use show hide function.
I hope this can help you.
Here is another option:
We manually submit the form based on what the user clicks in the confirmation box
function showSpinner(confirmed) {
if (confirmed) {
$('.spinner').css('display', 'block');
$('#formID').submit();
}
}
.spinner{ display: none; }
<input type="button" value="Search" id="searchbtn" class="btn btn-primary btn-block" onclick="showSpinner( confirm('Are you sure to proceed') )" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<h1 class="spinner">My spinner</h1>

Two Html buttons for two different functions

I have a form which has two Options, Submit and Overwrite.
It looks like this:
[ INPUT FIELD ]
[Submit] [Overwrite]
The Overwrite Button only appears when the value already is in the Database.
The HTML Code is:
<input type="text" name="target" id="target">
<button id="submit" name="submit" type="submit" class="btn btn-primary"> Submit </button>
<button id="overwrite" name="overwrite" type="submit" class="btn btn-primary"> Overwrite </button>
The JS Code is:
if(!problem){
data = "submit=save";
jQuery('#overwrite').click(function(){
$(this).toggleClass('selected');
if( $(this).hasClass('selected') ){
data+="&overwrite=on";
console.log( "overwrite=on" );
}
});
sendToBean(href, data);
jQuery.each(langs, function(i, lang){
sendToBean(href, data);
});
}
}
If I only have the Submit button, it works.
If I only have the Overwrite button, it works.
But if I have both, the Overwrite button wont work anymore.
Does anyone have a solution to this problem?
put retrun false in the anonymous callback function will do the trick. since you declare that the button is a submit button
if(!problem){
data = "submit=save";
jQuery('#overwrite').click(function(){
$(this).toggleClass('selected');
if( $(this).hasClass('selected') ){
data+="&overwrite=on";
console.log( "overwrite=on" );
}
return false;
});
sendToBean(href, data);
jQuery.each(langs, function(i, lang){
sendToBean(href, data);
});
}
}
When you click the submit button the page will be refreshed and the overwrite will return to the initial format and the selected will disappear, Try to change the input type to button :
<button id="overwrite" name="overwrite" type="button" class="btn btn-primary"> Overwrite </button>
Hope this helps.
Remove <input type=""> for Overwrite button you may use <button>
Overwrite
<input type="text" name="target" id="target">
<input type="submit" id="btnSubmit" name="btnSubmit" class="btn btn-primary" value="submit"/>
<input type="submit" id="btnOverwrite" name="btnOverwrite" class="btn btn-primary" value="Overwrite"/>
$(document).ready(function(){
$("#btnOverwrite").unbind("click").bind("click",function(e){
e.preventDefault();
alert("overwrite called");
});
$("#btnSubmit").unbind("click").bind("click",function(e){
e.preventDefault();
alert("submit called");
})
});
Review fiddle
https://jsfiddle.net/dipakchavda2912/rwdakvyg/

Disable/enable button using jquery

I have a button that will disable if a certain condition occurs. Its like when the order_status is Accepted then the button for Accept is disabled. Its same in the other buttons when the order_status is Pending then the Send button is disabled. How can I achieve that?
Whats happening right now is I can disable the button for ASD but when I change the #asd to #submitAccept it didn't disable the Accept button, how that's possible?
But for now, help me how can I achieve when the order_status is Accepted the Button for Accept is disabled. I hope you can help me guys with my prob, I don't know what to do. Really appreciate any help from you guys, Thanks!
Heres my code right now.
function viewOrder(order_id, order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("t_order_id").setAttribute("value", order_id);
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementById("t_user_id").setAttribute("value", user_id);
document.getElementById("t_order_date").setAttribute("value", order_date);
document.getElementById("t_order_time").setAttribute("value", order_time);
document.getElementById("t_order_deliveryCharge").setAttribute("value", order_deliveryCharge);
document.getElementById("t_order_totalAmount").setAttribute("value", order_totalAmount);
document.getElementById("t_address").setAttribute("value", address);
document.getElementById("t_coordinates").setAttribute("value", coordinates);
document.getElementById("t_drivers_number").setAttribute("value", driver_number);
document.getElementById("t_order_status").setAttribute("value", order_status);
document.getElementById("ORDER_MODAL_ACCEPT").setAttribute("value", order_id);
document.getElementById("ORDER_MODAL_DELIVER").setAttribute("value", order_id);
document.getElementById("ORDER_MODAL_CANCEL").setAttribute("value", order_id);
$(document).on("click", "#asd", function () { // MY JQUERY
if ($("#t_order_status").val() == "Accepted") {
$("#asd").prop("disabled", true);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="form-group">
<label for="order_status" class="col-sm-2 control-label" style="width:20%;">Order Status</label>
<input type="text" class="form-control" name="order_status" id="t_order_status" style="width:80%;" placeholder="" value="" required="required" readonly>
</div>
<button type="button" input style="background-color:#4CAF50;color:white;border-color:#000000;" name="submitDelivered" id="submitDelivered" class="btn btn-success" data-toggle="modal" data-target="#myDeliverModal" onclick="deliver('<?= $_POST['order_id'] ?>')" > Delivered </button>
<button type="button" input style="background-color:#0000FF;color:white;border-color:#000000;" name="submitAccept" id="submitAccept" class="btn btn-success" data-toggle="modal" data-target="#myAcceptModal" onclick="accept('<?= $_POST['order_id'] ?>')" > Accept </button>
<button type="button" style="background-color:#FFFF00;color:black;border-color:#000000;" class="btn btn-success" data-toggle="modal" data-target="#myDropdown" onclick="send('<?= $_POST['order_id'] ?>')"> Send </button>
<button type="button" input style="background-color:#f44336;color:white;border-color:#000000;" name="submitCancel" id="submitCancel" class="btn btn-success" data-toggle="modal" data-target="#myCancelModal" onclick="cancel('<?= $_POST['order_id'] ?>')">Cancel</button>
<button type="button" name="asd" id="asd" class="btn btn-primary" onclick="asd"> ASD </button>
Use the .disabled method and set it to true.
window.onload = function() {
if(document.getElementById("t_order_status").value == "Accepted") {
document.getElementById("asd").disabled = true;
}
}

Multiple submit buttons in angular2 form

I am building angular2 form and I would like to have multiple buttons to submit the form, e.g "Save" and "Save and close".
I have tried to use simple buttons with click action on them, but I didn't find anyway to manually mark form as submitted to force form validation.
<form #ticketForm="ngForm" novalidate>
<input type="text" id="customerName" required
name="customerName" [(ngModel)]="ticket.customerName"
#customerName="ngModel">
<div class="tj-form-input-errors"
*ngIf="customerName.errors && (customerName.dirty ||
customerName.touched || ticketForm.submitted)">
<small [hidden]="!customerName.errors.required">
Customer name is required
</small>
</div>
<button type="button" (click)="save(ticketForm)">Save</button>
<button type="button" (click)="saveAndClose(ticketForm)">Save and close</button>
</form>
Assign different id to each button. Then you can obtain the id of the button which triggered submit using document.activeElement.id. like the following :
In your Html :
<form #form="ngForm" (submit)="firstSave(form,$event)">
...
<div class="form-group">
<input type="submit" id="submit-1" value="Submit 1" class="btn btn-sm btn-primary"/>
<input type="submit" id="submit-2" value="Submit 2" class="btn btn-sm btn-success"/>
</div>
</form>
Then in your typescript :
firstSave(form: NgForm, $event: Event) {
var activeButton = document.activeElement.id; // document.activeElement?.id
if (activeButton == "submit-1") {
alert("you have clicked on submit 1");
}
if (activeButton == "submit-2") {
alert("you have clicked on submit 2");
}
}
StackBlitz Here.
You can subscribe to form changes, which I think will fire form validation.
I do something like this:
this.physicalForm.valueChanges
.map((value) => {
return value;
})
.filter((value) => this.physicalForm.valid)
.subscribe((value) => {
do what you need with the values here...
});
Then in your click handler for each button, if this.physicalForm.valid you save or save&update.
i ran into the same situation. In my case i have 2 submit 'Save','Save and Allocate'
Solution
You can simply set the the type of submit button in the payload and do the action accordingly in the backend code.
Sample code
//here formData is my payload for the API call eg: formData.name,formData.email
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='save'">Save</button>
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='allocate'">Save And Allocate</button>

Reset Form / remove error classes from jQuery validate

i have a contact form with jQuery validate method. When the user click on "Reset"-button the hole contact form should be go to the initial state.
This is the button looks like:
<form class="form" method="post" action="" name="contact" id="contact">
<button type="button" id="cancel" class="btn btn-danger btn-lg">Reset</button>
</form>
And the JS-Code in my "$(document).ready-function" is:
$('#cancel').on('click', function () {
$("#contact").validate().resetForm();
$("#contact").removeClass("has-error");
});
Problem: The error Text and the Input-fields will be deleted. But the red border (.has-error) or the green border (.has-success) don't be deleted.
i've created an JSFiddle for you:
http://jsfiddle.net/bBc8c/1/
One Button is clear the input text, the other is delete the error Messages.
I need a Button which reset both (Text, Error Message) and the main problem the red border from the has-* classes.
One Button is declared as type=submit the other is type=button:
<button type="button" id="cancel" class="btn btn-danger btn-lg">Reset 1</button>
<button type="reset" id="cancel2" class="btn btn-danger btn-lg">Reset 2</button>
Your Updated Fiddle
JS Update
$('#cancel').on('click', function () {
$("#contact").validate().resetForm();
$("#contact").find('.has-error').removeClass("has-error");
$("#contact").find('.has-success').removeClass("has-success");
$('#contact').find('.form-control-feedback').remove()
});
For bootstrapvalidator, this might useful when the form being display via bootstrap modal,
$("#editModal").on('hidden.bs.modal', function () {
//Removing the error elements from the from-group
$('.form-group').removeClass('has-error has-feedback');
$('.form-group').find('small.help-block').hide();
$('.form-group').find('i.form-control-feedback').hide();
});
#J Santosh answer worked for Bootstrap 3, great work.
For Bootstrap 4 I have done following changes:
$('#cancel').on('click', function () {
$("#contact").validate().resetForm();
$("#contact").find('.is-invalid').removeClass("is-invalid");
$("#contact").find('.is-valid').removeClass("is-valid");
$("#contact").find('.invalid-feedback').remove();
$("#contact").find('.valid-feedback').remove();
});
Simply have to change the class names. Hope it helps!
I'd reset the form by just using an input[type="reset"] (no jQuery required)
<form class="form" method="post" action="" name="contact" id="contact">
<input type="reset" class="btn btn-danger btn-lg" />
</form>
i've created an JSFiddle for you:
http://jsfiddle.net/bBc8c/1/
One Button is clear the input text, the other is delete the error Messages.
I need a Button which reset both (Text, Error Message) and the main problem the red border from the has-* classes.
One Button is declared as type=submit the other is type=button:
<button type="button" id="cancel" class="btn btn-danger btn-lg">Reset 1</button>
<button type="reset" id="cancel2" class="btn btn-danger btn-lg">Reset 2</button>
Regards

Categories

Resources