Button Firing 2 Scripts instead of 1 - javascript

I have a table which allows users to make a selection from a list of items and stores the selected ID in a hidden form input, and then a submit button which validates to make sure the hidden form input is not empty.
Here's the HTML showing a single row and the submit button:
<tr class="" id="PR7518">
<td>1234A</td>
<td>Option A</td>
<td class="text-center">
<button type="button" class="btn btn-success btn-sm">Select</button>
</td>
<div class="text-center">
<button type="submit" name="buttonType" value="saveSelected" class="btn btn-success">Submit</button>
</div>
The submit button is invoking both of the following scripts, when I only want it to invoke the form submit (2nd script):
$(document).ready(function() {
$('button.btn-success').click(function() {
$('#productID').val(productID);
});
});
$("form").submit(function(event) {
event.preventDefault();
if ($('#productID').val() == '') {
$("#productID_Error").show();
return false;
}
});
Not sure what change I need to make to prevent the submit button from invoking the first script?

The first selector $('button.btn-success') is selecting both of the buttons since they both have the class 'btn-success'. You need to add some sort of unique identifier to the first button so that you can select it without getting both buttons. You can do this by adding another class or id to the first button and then adjusting your selector to point to that unique identifier.

You can add :not([type="submit"]) to your selector in the first script to exclude the submit button.
$(document).ready(function() {
$('button.btn-success:not([type="submit"])').click(function() {
$('#productID').val(productID);
});
});

Related

Why is HTML 5 validation triggering when I run Jquery function

I have a button that triggers the below jquery function. Currently the function works and hides/shows the form element as desired. However it is tripping the html 5 validation (which I want on submit). Is there a reason it is triggering and a way I can prevent this? I experimented with having a return at the end of the function but no luck. Also neither form is required as part of the validation. I keep getting a pop up telling me previous items are required when I hide/show the form elements..
<button class="col-sm-2 btn btn-success" onclick ="hideFormField ()">Hide</button>
function hideFormField (){
if(!$("#trail").is(":visible"))
{
$("#trail").show();
$("#blazers").hide();
}else{
$("#trail").hide();
$("#blazers").show();
}
}
Try this:
<button class="col-sm-2 btn btn-success" onclick ="hideFormField ();return false;">Hide</button>
Try:
<button class="col-sm-2 btn btn-success" onclick="hideFormField();event.preventDefault();">Hide</button>
Jonathan Lonowski was correct in his comment. Buttons are submit-type by default so you need to explicitly define a button with type="button" attribute if you don't want any additional effects when the button is clicked.
A small example that illustrate the activation of HTML5 form validation through default button behavior is in this jsfiddle: http://jsfiddle.net/zk3jr9vn/
by default button is submit type so add Type to button
like
<button type="button" class="col-sm-2 btn btn-success" onclick ="hideFormField ()">Hide</button>

Redirecting button after selection

I have two buttons (describing the type of delivery). Once selected I have to press another button to proceed . Is there any way how I can proceed automatically after selection?
Here is my code before selection:
<button type="button" class="button btn-delivery-method" data-delivery-method="s_method_free">
<span class="btn-delivery-method__label">Select</span>
</button>
Here is my code after selection:
<button type="button" class="button btn-delivery-method delivery-method__selected" data-delivery-method="s_method_free">
<span class="btn-delivery-method__label">Select</span>
</button>
Here is my third button to proceed:
<button type="button" class="button btn-large--alt" onclick="shippingMethod.save()">
Continue
</button>
Thanks
You can add the onclick event to the first two buttons.
Btw, what does the code do after pressing either of the first two buttons?
Bind a click event to the first button as well:
$(".button.btn-delivery-method").click(function() {
// check if the delivery has been selected
if($(this).hasClass("delivery-method__selected")) {
// either call shippigMethod.save(); here
//trigger the button click
$(".button.btn-large--alt").trigger("click");
}
});
This will trigger the button only when the delivery is selected
if($(this).hasClass("delivery-method__selected")) {
$(".button.btn-large--alt").trigger("click");
}
It would be nice to have the Id from your second button just to avoid any conflicts with other buttons.

How to handle multiple submit buttons in a form using Angular JS?

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form and then reset it - allowing them to enter another entry.
How do I accomplish this in angular? I was thinking I could have two submit buttons with ng-click tags, but I'm using ng-submit on the form element. Is there any reason I NEED to be using ng-submit - I can't remember why I started using that instead of ng-click on the button.
The code looks something like:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button type="submit">Save and Add Another</button>
</form>
</div>
And in the controller SomeController
$scope.record = {};
$scope.save = function (record) {
$http.post('/api/save', record).
success(function(data) {
// take action based off which submit button pressed
});
}
You can keep both ng-click and type="submit". In the ng-click you can just update a parameter of your controller and validate that in the event ng-submit:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button type="submit" ng-click="SaveAndAddClick=true">Save and Add Another</button>
</form>
So this approach avoids you from adding a method and then calling a redundant code.
Thanks
ngSubmit allows you to press Enter while typing on the textbox to submit. If that behavior isn't important, just use 2 ngClick. If it is important, you can modify the second button to use ngClick. So your code becomes:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button ng-click="saveAndAdd(record)">Save and Add Another</button>
</form>
</div>
Make them all buttons and type=submit. It makes it a little cleaner not mixing and matching inputs and buttons. So basically you're trying to execute one method in your controller to handle either button click.
<div ng-controller="SomeController as sc">
<form ng-submit="sc.execute(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit" ng-model="sc.saveButtonVal" ng-click="sc.saveButtonVal=true>Save</button>
<button type="submit" ng-model="sc.saveAndAddButtonVal" ng-click="sc.saveAndAddButtonVal=true">Save and Add Another</button>
</form>
</div>
So, in your js file you'll have something like this.
function SomeController() {
var sc = this;
sc.execute = function(record) {
//initialize the vars
sc.saveButtonVal = false;
sc.saveAndAddButtonVal = false;
sc.resetButtonValues = function() {
sc.saveButtonVal = false;
sc.saveAndAddButtonVal = false;
};
if (sc.saveButtonVale) {
//do save only operation
} else if (sc.saveAndAddButtonVal) {
//do save and add op
}
// reset your button vals
sc.resetButtonValues();
}
}
As I see it, you have two options:
1: Use an ngClick event on the "save and add another" button and remove the "type='submit'" portion. Then in whatever function you call gor the ngClick, you can save and then reset the values, calling save() within that function.
2: Remove the ngSubmit altogether and just use ngClicks for both buttons.
If someone looking for a simple approach then just create a flag and toggle between button and submit.
<button type="{{isButton == true ? 'button' : 'submit'}}" >Save</button>
<button type="{{!isButton == true ? 'button' : 'submit'}}" >Update</button>
Need to handle the flag according to user action.
ng-submit has other advantages too. For example, invalid form will not be submitted. It is always better to use ng-submit instead of ng-click. However, in your scenario, better approach would be
use ng-click on buttons.
validate form in controller. Keep in mind that ng-click will submit the form even if it is not valid.
call two different $scope.functions on two different ng-click in the somecontroller.
Hope it helps.
Remove ng-submit from "form" element and define ng-click functions separately on each button with type 'submit'.For invalidation check, define name property in form element tag. And check validation in scope function.
<div ng-controller="SomeController">
<form name="saveForm">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit" ng-click="save(record)">Save</button>
<button type="submit" ng-click="saveOther(record)">Save and Add Another</button>
</form>
Scope Function:
$scope.record = {};
$scope.save = function (record) {
if(this.saveForm.$valid)
{
$http.post('/api/save', record).
success(function(data) {
// take action based off which submit button pressed
});
}
}

Cross browser solution for submit buttons outside form

I am basically trying to implement this
http://www.impressivewebs.com/html5-form-attribute/
I have a cart which is outputting and sandwiched by a html table. Below the table, I currently have my submit button.
<thead>
<tr>
<th>ITEM</th>
<th>PRICE</th>
<th>WEIGHT (Kg)</th>
<th>QTY</th>
<th>SUBTOTAL</th>
<th></th>
</tr>
</thead>
<tbody>
<form action='shop.php' id='cart' method='post'>
<?php echo $cartOutput; ?>
</form>
<tr>
<td class="totals"><strong>Total</strong></td>
<td class="totals"> </td>
<td class="totals"><?php if (isset($weightTotal)) { echo $weightTotal . 'kg';} ?> </td>
<td class="totals"><?php if (isset($quantityTotal)) { echo $quantityTotal; } ?></td>
<td class="totals"><strong><?php if (isset($cartTotal)) { echo '$' . $cartTotal; } ?></strong></td>
<td class="totals"></td>
</tr>
</tbody>
/* code finishing table here */
<div class="col-lg-12 col-md-12 col-xs-12 remove-padding">
<button type="submit" class="btn btn-default" form="cart" name="adjustButton" id="adjust-button">UPDATE CART</button>
<button type="button" class="btn btn-default" form="contact" name="order" id="order-button" onclick="confirmOrder()" >ORDER NOW</button>
</div>
So because of the way I want the layout to look.. I can't put the buttons inside the form. I want to have the ability to put the update button below the cart.
Right now the order button is not a submit button but just a button. I can put it beneath its own form section but right now I force it through javascript for a confirmation and then submit the request through JS if they say OK.
I want to keep that function while supporting browsers including IE 9 +10. From what I found form="" doesn't work in IE
Can I achieve this?
Put the form tag outside all 'relevant' content (including submit button(s)):
<body>
<form>
<table>
</table>
<div>
<button>
</button>
</div>
</form>
</body>
If the button cannot be inside the form, make the form outside the
button.
This should work in all browsers:
document.getElementById('cart').submit();
You can put that in the onClick, and wrap it in a function if needed.
Edit: Since the issue (per the comments below) is that you have inputs outside the form: Really the simplest solution, and one that involves no Javascript, is to put the </form> at the end of the page (so that all your inputs and buttons will be in the form). But of course this doesn't work if you need to have more than one form on the page, and it might not even be possible depending on how the page is layed out.
If your submit button is outside the form and you have some input elements outside the form then the simplest way to send this form (without using ajax) would be to make a form and put your submit button in it.
And since your input fields are outside the form you will make a copy of those input fields inside your form and hide them with display:none; and when user changes the value of your visible input fields you will use javascript to change the value of the hidden input field.
This way you get to send the form the usual way, without the input fields having to be inside the form itself.....
You could copy the outside form elements to inside the form and sync them using JS.
http://jsfiddle.net/rudiedirkx/y0cmda4o/
if ( !('fform' in document.createElement('input')) ) {
$('input[fform], textarea[fform], select[fform]').on('change', function(e) {
this.$hidden.val(this.value);
}).each(function(i, el) {
var formId = $(el).attr('fform'),
$form = $('#' + formId),
$hidden = $('<input name="' + el.name + '" type="hidden">');
$form.append($hidden);
el.$hidden = $hidden;
});
}
As you can see, I used the fform attribute, to trigger the if statement. Change it to form and try it in IE.
Disclaimer:
This won't work with multiple value elements (like select[multiple]), or you have to add some serious JS to fake those multiple values.
This won't send the triggered button value. Normal submit buttons send only their value, and not the other submit buttons'. You could maybe add an onclick to handle that... If you use it.

I have two forms in a page. How to set the jQuery script not to affect both forms buttons?

In my page I have 2 forms. he jQuery scripts disables both buttons of the forms, until one dropdown value is selected as you can see here http://jsfiddle.net/baW53/
The problem is that I need to activate only the button where the dropdown value is changed/selected. For now if I choose a value on the first form, it activates the button of the second form also. But it has to activate only the same form's button.
How to do this?
var jq = $.noConflict();
jq(document).ready(function (){
validate();
jq('select').change(validate);
});
function validate(e){
var validation = true;
jq('select').each(function(){
if(jq(this).val().length>0)
{
validation = false;
}
});
if ( validation ) {
jq('.submit').prop('disabled', true);
} else {
jq('.submit').prop('disabled', false);
}
}
<form name="forma" method="POST" action="used-results.php" id="apliforma">
dropdown menus
<button type="submit" class="btn btn-primary submit" id='submit' >submit</button>
</form>
<form name="forma2" method="POST" action="used-results.php" id="sinthetiforma">
dropdown menus
<button type="submit" class="btn btn-primary submit" id='submit2' >submit</button>
</form>
You have to use selectors like others say. Here's the modification to your jsfiddle: http://jsfiddle.net/baW53/1/
Basically, if its the initial call, we change the properties of all the buttons, i.e, buttons with class submit else we find the button which is a sibling of the dropdown and use its id.
Here's the relevant portion:
if (e) {
var btn = "#" + jq(this).siblings('button').attr('id');
} else {
var btn = ".submit";
}
You are selecting every submit button with this selector jq('.submit') you need to make it more specific. There are any number of ways to do this.
One way is to get the select control from your event object then write a pattern to go to it's parent form and then down to the select button.
Getting the closest form:
jQuery find parent form
jq(ev).closest("form").find(".submit")
I'm not sure that ev is right, you might have to dig the control out of the event.
You can find specific elements with more complex selectors. For instance, if you gave your forms id="forma" and id="formb" you could do jq(#forma .submit) to get the one button.
If you stick with the name attribute, I believe the selector would be jq([name="forma"] .submit) or something close to that.

Categories

Resources