Javascript onclick function stops HTML5 required from working - javascript

Good day,
I am working on a form where all my text fields have a required attribute; I noticed that when i clicked on submit required attribute does not show a pop up to validate if a field is empty.
I have two submit buttons on my page both using an onclick submitform function; One opens up a new tab and the other submits the form and goes to a new page.
For debugging purposes i remove the button that opens up a new tab and remove the onclick attribute on my second button and it work; I have been googling all day but i cannot seem to find the same scenario i have at the moment.
I believe it has to do with my JS but i am not sure what to add or remove on my code; Please see my code below.
JavaScript
function submitForm(action,newtab)
{
document.getElementById('add2').target = newtab ? '_blank' : '_self';
document.getElementById('add2').action = action;
document.getElementById('add2').submit();
}
HTML
<form id="add2" action="add5.php" method="post">
<input placeholder="First Name" tabindex="1"
name="fname" maxlength="128" size="30" required>
<input placeholder="Last Name" tabindex="12"
name="lname" maxlength="128" size="30" required>
<button tabindex="3" value="Save"
name="save" onclick="submitForm('add3.php',1);"
type="submit">Child Information</button>
<button tabindex="4" value="Save"
name="save" onclick="submitForm('add5.php',0);"
type="submit">Save Details</button>
</form>
I have a button attribute but i have set it to type="submit" and i am pretty much sure that works as i have already tested it when i removed the onclick functions; My question is can i required attribute worked without removing the onclick function of JavaScript?
Any help is much appreciated.

I found the answer to my question, The problem is that i was binding onClick method to the submit. The onClick will trigger first which results in it getting past the validator.
Solution is i change the onClick to onSubmit on my HTML code.
<button tabindex="3" value="Save"
name="save" onsubmit="submitForm('add3.php',1);"
type="submit">Child Information</button>
<button tabindex="4" value="Save"
name="save" onsubmit="submitForm('add5.php',0);"
type="submit">Save Details</button>

You just need to use the "checkValidity()" method on the form before submitting in your onclick function like this:
if($("#add2").checkValidity()) {
document.getElementById('add2').submit();
}
See this fiddle: http://jsfiddle.net/36uv2e52/33/

Rather than using required you can simply check the values before you submit.
function submitForm(action,newtab) {
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
if (fname == "" || lname == "") {
alert("First and last name are required");
exit;
} else {
document.getElementById('add2').target = newtab ? '_blank' : '_self';
document.getElementById('add2').action = action;
document.getElementById('add2').submit();
}
}

Related

How to make my reset button work in HTML without the form?

here is my code
I have tried using javascript with onClick but then my submit button won't work. Then I tried changing it into the normal button and it still won't work. I tried putting it into the form and still won't work. So, I don't know how to reset the button for my form. This is my school work and I'm still a student so please help me. I would appreciate your help soo much.
The Form types: reset and submit need a context. I mean you have to wrap all inputs inside a form. <form>....</from>. Then reset has the context to reset all fields inside his context / form.
Otherwise if you dont want use form you can do it by Javascript.
function reset() {
document.getElementById('input_1').value = ''
document.getElementById('input_2').value = ''
}
<input id="input_1" value="Hello"><br/>
<input id="input_2" value="World">
<br/>
<button onclick="reset()">RESET</buton>
You should use javascript for reset your inputs
Notice: Keep in mind that the Enter key also works when using the form
<div>
<div id="like-form">
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
</div>
<button type="button" id="like-reset">
Reset
</button>
</div>
You can use Ajax to submit information, But to reset
document.getElementById("like-reset").addEventListener("click" () => {
// forEach
[].slice.call(document.getElementById("like-form").children).forEach(input => {
input.value = "";
});
// For
const inputs = document.getElementById("like-form").children;
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
});
U should set all inputs and reset button inside form.
Like so:
<form>
<input type="text">
<input type="reset" value="Reset">
</form>
That way it should work.

Conditional Required Validation with buttons in AngularJS

I having two buttons as Save and Submit and some of the drop-downs and text-boxes. There is need to validate some of the fields on click of Submit, not on click of Save. Please find the code in below.
<button class="btn btn-default custom_edit"
data-ng-click="orderForm.$valid && saveOrder('save')"
data-ng-if="!order.IsSubmitted"
data-ng-model="status"
value="save">Save</button>
<button class="btn btn-success"
data-ng-click="orderForm.$valid && saveOrder('submit')"
data-ng-if="!order.IsSubmitted"
data-ng-model="status"
value="submit">Submit</button>
<input type="text" class="form-control" name="_requisition" placeholder="Requisition"
data-ng-model="order.Requisition"
data-ng-trim="true"
data-ng-required="status=='save'"/>
I have tried by using value & model with buttons and applied it with ng-required , however it's not working.
Using input type as 'submit', validation can be maintained as well as other function can be also called as form is valid.
<input type="submit" value="Save"
data-ng-click="isSave = true; orderForm.$valid && saveOrder('save')"
data-ng-model="isSave"
data-ng-show="!order.IsSubmitted"/>
<input type="submit" value="Submit"
data-ng-click="isSave = false; orderForm.$valid && saveOrder('submit')"
data-ng-model="isSave"
data-ng-show="!order.IsSubmitted"/>
<input type="text" class="form-control" name="_requisition" placeholder="Requisition"
data-ng-model="order.Requisition"
data-ng-trim="true"
maxlength="100"
data-ng-required="isSave"/>
So by this way, we can easily set model value on button click at run time as well as can validate form.

How to reset form fields the elegant way with javascript or jquery?

How do I reset the form fields more elegant compared to the code below? The code is working. But if I have lots of form fields it does not look so nice. Is there a more compact way?
<script>
function setSearchCriteria(){
var searchcriteria = document.getElementById("TherapistSearch-SearchCriteria");
searchcriteria.value = "";
}
function setCity(){
var city = document.getElementById("TherapistSearch-City");
city.value = "";
}
function setLastName(){
var lastname = document.getElementById("TherapistSearch-LastName");
lastname.value = "";
}
function setFirstName(){
var firstname = document.getElementById("TherapistSearch-FirstName");
firstname.value = "";
}
}
</script>
<input type="button" class="btn btn-default" value="Reset form"
onclick="javascript:clearForms();javascript:setSearchCriteria();setCity();setLastName();setFirstName();" title="Reset form"/>
Give a css class to your input fields.
<input type="text" id="firstName" class="resettable" />
<input type="text" id="firstName" class="resettable" />
<select id="states" class="selectResettable">
<option value="0">Select an option </option>
<option value="1">Michigan</option>
<option value="2">Ohio</option>
<select>
<input type="button" id="resetBtn" />
And use this css class(es) as jQuery selector(s) to get all of this inputs and set the value to empty/default value. I also removed the onclick from button HTML markup as we are going to do it in the unobtrusive javascript way.
Add this javascript where we are registering the code for the click event on our button.
$(function(){
$("#resetBtn").click(function(e){
alert("Reset button clicked");
//Set the input text fields to empty string
$("input.resettable").val("");
//Reset the dropdowns.
$(".selectResettable").val("0")
//If you want to do something else, Do it here.
});
});
Simply use HTML the way it's meant to be used, and take advantage of the reset button:
<input type="reset" class="btn btn-default" value="Reset form" title="Reset form"/>
This requires no JavaScript, no additional functionality, and is a native component of HTML forms. Using type="button" gives the element the appearance of a button, but strips the default functionality; using type="reset" gives the appearance of a button and gives the default functionality of resetting the parent <form> element to its default page-load state.
References:
<input> element type attribute-values.
<input type="reset" id="resetBtn" class="resettable" />
use reset type of button or call reset method on form as below
<input type="button"
class="btn btn-default"
value="Reset form"
onclick="document.getElementById('myForm').reset();"
title="Reset form"/>

HTML Form, getElementById not working inside javascript function. Login Page

I am confused here, I have html form from which I want to send information to javascript. (which will call offisde for login). Everytime I enter var username = document.getElementById("user").value; inside the function, nothing appears on my console log. But if I take that out, it behaves as normal.
Here my html
<form class="form-login">
<h2 class="form-login-heading">sign in now</h2>
<div class="login-wrap">
<input type="text" class="form-control" placeholder="User ID" name="user" autofocus>
<br>
<input type="password" class="form-control" placeholder="Password" name="passwd" >
<button class="btn btn-theme btn-block" Value="Submit" type="submit" onclick="Calculate()"><i class="fa fa-lock"></i> SIGN IN</button>
Here my javascript
<Script>
function Calculate(){
console.log("In function, test 1");
var username = document.getElementById("user").value; <-- if remove this, console/alert apper, but add this and no consoles.log appear. Not even the one above
alert ("Login successfully");
window.location.replace("index.html");
//window.location = "index.html"; // Redirecting to other page.
return false;
</script>
So I am confused on why I cannot used getElementById inside my javascript function.
`
There is no element with id user, you have an input with name user, add attribute id="name" to it and tthen you should be fine.

How do i create a simple Javascript Program that displays the value of <input type="text">?

I am new to javascript, and i only know c++ so far, but i know the logic but i just don't know the syntax on javascript
so i have this form :
<span>Please type your name here: </span>
<input id="inputname" type="text" value=""></input>
when the user types his/her name how do i save the value to some variable and display it with javascript?
i have already tried using
function displayName(){
var username = getElementById("inputname").value;
document.write(username);
}
and i put
<script>displayName();</script>
below the form. it doesn't seem to work, how do i do it?
and how do i use:
<input type="submit"></input>
in relation to it?
Try this,
Javascript
function displayName(){
var username = document.getElementById("inputname").value;
document.getElementById("msg").innerHTML = username;
}
HTML
<span>Please type your name here: </span>
<input id="inputname" type="text" value=""></input>
<input type="button" onclick="displayName();"></input>
<span id="msg"></span>
By changing onclick="return displayName()" to onkeypress="displayName()" you will be able to see the changes on the spot.
change your html and js like this. onblur function call when user leaves the input from focus. get the enter value onblur
<span>Please type your name here: </span>
<input id="inputname" type="text" onblur="displayName();" value=""></input>
js
function displayName(){
var username = document.getElementById("inputname").value;
document.write(username);
}
you need to change your fucntion little bit..
getElementById() is not a direct function in javascript..use it with document object
function displayName(){
var username = document.getElementById("inputname").value;
document.getElementById("msg").innerHTML = username;
return false;
}
on submit click
<input type="submit" id="btnSave" onclick="return displayName();" value="Save" />
<div id="msg" > </div>

Categories

Resources