Why is HTML 5 validation triggering when I run Jquery function - javascript

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>

Related

sign up button disappear after page refreshing

I have problem with sign up button while registering as user, Actually there is check box for T&c. After checking that check box only button should enable.
Everything is going well But, when I am refreshing page I am not able to see button, I able to see all other elements even check box.
here are Html tags I used for check box and Sign Up button and I also used flags.
<p class="terms"> <div class="chckbx-cntnr zeromargin" style = "padding:2px;vertical-align:middle"><input type="checkbox" id="rd" name="check" class="flashadmin" ng-model="user.tnc" ng-click="setbuttonFlag(user.tnc)" class="flashadmin"><label class="cstmchk_lbladmin" for="rd"></label></div>
I agree to the Terms of Use and Privacy Policy.</p>
<button ng-if="buttonFlag==true" id="signup"class="btn btn-default btn-block btn-login" type="submit" >Sign up</button>
<button ng-if="buttonFlag==false" id="signup" class="btn btn-default btn-block btn-login" disabled >Sign up</button>
here is validation i wrote for flag
$scope.buttonFlag=false;
$scope.setbuttonFlag =function(checkbox){
if(checkbox == true){
$scope.buttonFlag=true;
}else{
$scope.buttonFlag=false;
}
};
I am getting in console
Error: $injector:unpr
Unknown Provider
First thing is your code looks clumsy!
Below mistake you did, you misunderstood the concept completely.
Why you required for two submit button in your html? Also no need separate click event for changing button flag.
Now coming to your question:
When I am refreshing page I am not able to see button
This is because your are using ng-if directive in button element at the same time while initiating your controller you set $scope.buttonFlag=false so obviously you can't see button while refresh..
Below snippet will work for you!
angular.module("app", []).controller("testCtrl", function($scope) {
$scope.buttonFlag = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="testCtrl">
<input type="checkbox" ng-model='buttonFlag'> I agree to the Terms of Use and Privacy Policy.
<button ng-disabled='!buttonFlag' id="signup" class="btn btn-default btn-block btn-login">Sign up</button>
</div>
</div>
Well upon refresh you are manually setting buttonFlag to false hence the button disappears.Store buttonFlag in localStorage and check the state of buttonFlag unlike setting it to false as you have done.
if(localStorage.getItem('buttonFlag')){
buttonFlag = localStorage.getItem('buttonFlag');
}
else{
buttonFlag = false;
}
also instead of using two different button for signup use ng-disabled to disable or enable a button

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

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.

How to disable a submit button after one click?

I have this form inside a div and the submit button inside another div.
<div class="container1">
<form name="reg-form" id="signup" action="" method="post">
<div class="sep"></div>
<div class="inputs">
<input type = "submit" id="submit" name="submitkey" value="GENERATE KEY" />
</div>
</form>
</div>
How would I disable the submit button after one click? I tried every javascript code I find but it doesn't work on me. I dont know if it is because the form is inside a div and the submit button is inside another div. Thank you.
document.getElementById('signup').onsubmit = function() {
document.getElementById('submit').disabled = true;
};
Demo
The code should be put under the script, or wrapped inside a DOMContentLoaded/window.onload handler. Make sure your HTML does not have duplicated IDs.
Also, if the button must stay disabled after a page refresh/form submission, you will need cookies or a server-side session. None of these methods are foolproof though, and this is outside of the scope of the question I believe.
If you have jquery you can use this code:
$('#signup').submit(function(){
$('#submit').attr('disabled', 'disabled');
});

How to use jQuery to submit a form and specify which submit button to use

Suppose a form has multiple submit buttons:
...
<button type="submit" value="deletefoo">Delete Foo</button>
<button type="submit" value="deletebar">Delete Bar</button>
<button type="submit" value="Edit">Edit</button>
...
I am intercepting the clicks for only the 2 delete buttons and disabling the form submit to trigger a custom modal dialog which has OK and CANCEL buttons on it to confirm user choice. If user presses OK, I want to submit the form. If cancel, then dialog dismissed and nothing happens.
I have the first part wired up to trigger the dialog but I am at a loss on how to get the OK button in the dialog to trigger the form submit contingent on which original submit button was pressed (e.g. if Delete button pressed, I want to confirm with user they want to delete, then if so, submit the form as normal.
I've searched around and look at jQuery docs but haven't found the answer yet so I must be missing something really straightforward.
Update: I don't want to use JS confirm function. In my original question above I'm looking to use a custom modal dialog for various reasons.
Check out the JS confirm function and put it as an onclick event.
You have a nice example here.
Why not have them be regular buttons and then onclick set a variable to determine the action type and then when the form submits include this hidden variable and check that to find what you're supposed to do
First, you'd have to intercept both (all) the buttons, you could do this easily by fetching any of the submit buttons within a specific form, then you can ask your question and given you still have the current event handler, you can figure out what button was pressed and do the callback you'd like. For example:
<form id="myform">
<button type="submit" value="delete">Delete</button>
<button type="submit" value="Edit">Edit</button>
</form>
--
$(function() {
$("form#myform button[type='submit']").click(function(ev) {
ev.preventDefault();
if (confirm("you sure")) {
var action = $(ev.currentTarget).val();
console.log(action);
}
});
});
JSLint is here: http://jsfiddle.net/r48Cb/
Basically, console.log(action) will output either "delete" or "Edit" based on the original click. How you handle that value is up to you. A switch statement, a simple if block could work, but it's up to you, I don't know the scope of your app.
The window.confirm function returns a true if the user selects okay and a false if the user cancels. Using this logic you could do something like this:
<button id="delete" type="submit" value="delete">Delete</button>
<button type="submit" value="Edit">Edit</button>
var question;
$("#delete").click(function(){question=window.confirm("Are you sure?");)
if (question){
//Submit the form here
}
else{
alert("Not deleted!");
}
I think you are making it too complex, you can do something as simple as:
<form >
<input name="foo" value="foo">
<button name="sub0" value="sub0" onclick="
return window.confirm('sure?');
">submit 0</button>
<button name="sub1" value="sub1" onclick="
return window.confirm('sure?');
">submit 1</button>
</form>
If the user clicks OK on the confirm dialog, the form submits from whichever button was pressed. If not, it doesn't.
My 2c:
... (edited: removed the value parameter. buttons don't need that)
<button onclick='deleteFoo(); ' >Delete Foo</button>
<button onclick='deleteBar(); ' >Delete Bar</button>
<button onclick='allowEdit(); ' >Edit</button>
...
function deleteFoo() {
do-your-modal-whichever-way-you-want;
if confirmed,
$('#form-id').attr('action','your-action-for-delete-foo');
$('#form-id').submit();
else-just-return
}
function deleteBar() {
do-your-modal-whichever-way-you-want;
if confirmed,
$('#form-id').attr('action','your-action-for-delete-bar');
$('#form-id').submit();
else-just-return
}
function allowEdit() {
whatever
}

Categories

Resources