validating textboxes prior to submission - javascript

I am trying to make a button that checks that there is text in each textbox using JavaScript. It will send an alert if they are not all completed and send another if they are. I'm not too sure how to do this and would like some help completing it. The name of the button and three textboxes are shown below.
<input id="checkD" type="button" value="Check Completion">
<input name="nameD" type="text" /><br>
<input name="emailD" type="text" /><br>
<input name="phoneD" type="text" /><br>

Add onclick event on button and validate all textbox values
<input id="checkD" type="button" onclick="validateTextbox();" value="Check Completion">
Please see below fiddle for reference
https://jsfiddle.net/ganesh2412/3ck6a09z/

one approach to accomplishing your task is by using document.querySelectorAll to select all the input elements of type text then simply loop through to check if each individual element has a length greater than 0 then simply display a message according to the outcome.
function validate(){
var inputElements = document.querySelectorAll("#testing input[type=text]");
var flag = true;
for (var i = 0; i < inputElements.length; i++){
if (inputElements[i].value.length == 0){
alert("please fill all fields");
flag = false;
break;
}
}
if(flag) alert("proceed...");
}
<form id ="testing" action="/action_page.php">
<input id="checkD" type="button" value="Check Completion" onclick="validate();">
<input name="nameD" type="text" /><br>
<input name="emailD" type="text" /><br>
<input name="phoneD" type="text" /><br>
</form>

Related

Autofocus on each textbox when not required field

I have a page with multiple text boxes, all of which are not required fields (i.e. the user can fill out as many as they wish to). However, I am not able to get autofocus to work from the second text box onwards and the form submits instead when I press enter to move into the next text box (probably because the inputs are not required). Is there a way such that I will be able to autofocus into the next text box after keying in the response for the previous textbox even if the field is not required/stop the form from submitting? Thanks for any help!
<html>
<main>
<form>
<br><label for="response1"><b>Animals</b></label><br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus ></br>
<br><input type="text" id="response2" name="response2" autocomplete="off" ></br>
<br><input type="text" id="response3" name="response3" autocomplete="off" ></br>
<br><input type="text" id="response4" name="response4" autocomplete="off" > </br>
<button type="submit">Submit</button>
</form>
</main>
</html>
try doing this, its supposed to make the enter to submit only on the last input, and the other times it just moves to the next input.
Dont forget to add the onkeydown to all the inputs except the last one.
<form>
<br><label for="response1"><b>Animals</b></label><br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus onkeydown="next(this, event)"></br>
<br><input type="text" id="response2" name="response2" autocomplete="off" onkeydown="next(this, event)"></br>
<br><input type="text" id="response3" name="response3" autocomplete="off" onkeydown="next(this, event)"></br>
<br><input type="text" id="response4" name="response4" autocomplete="off"> </br>
<button type="submit">Submit</button>
</form>
<script>
function next(currElement, e) {
if (e.keyCode === 13) {
e.preventDefault();
let nextNum = parseInt(currElement.id.substr(8)) + 1;
document.getElementById('response' + nextNum).focus();
return false;
}
}
</script>

HTML Button - How to dynamically change url content

I am trying to change values in a button's URI to input texts values.
<div class="numcontainer">
<input required="required" onchange="getNumber()" id="cnt" type="input" name="input" placeholder="ISD">
<input required="required" onchange="getNumber()" id="wano" type="input" name="input" placeholder="Enter number">
</div>
<button type="submit" name="gowa" id="btngo" onclick="location.href='myserver://send?phone=NumberPlaceHolder'">Go!</button>
NumberPlaceHolder: Trying to concatenate values enter in both input
JS:
function getNumber() {
document.getElementById('btngo').href.replace("NumberPlaceHolder",document.getElementById('cnt').value+document.getElementById('wano').value);
}
It does not work as expected. How can I solve this?
Just an alternative, it's cleaner
const getNumber =()=> {
let val =id=> document.querySelector(id).value
console.log('myserver://send?phone='+val('#cnt')+val('#wano'))
}
//console or location.href
<div class="numcontainer">
<input required id="cnt" type="text" placeholder="ISD">
<input required id="wano" type="number" placeholder="Enter number">
</div>
<input type="button" name="gowa" id="btngo" onclick="getNumber()" value="Go!">
onChange is quite unnecessary.
You cannot have a href attribute for a button. You need to change the onclick attribute here:
function getNumber(){
document.getElementById('btngo').setAttribute("onclick", document.getElementById('btngo').getAttribute("onclick").replace("NumberPlaceHolder", document.getElementById('cnt').value+document.getElementById('wano').value));
}
It's always better to have it split like this:
function getNumber(){
curOnclick = document.getElementById('btngo').getAttribute("onclick");
wanoValue = document.getElementById('cnt').value+document.getElementById('wano').value;
newOnclick = curOnclick.replace("NumberPlaceHolder", wanoValue);
document.getElementById('btngo').setAttribute("onclick", newOnclick);
}
You should use simple
instead of
<button type="submit" name="gowa" id="btngo" onclick="location.href='myserver://send?phone=NumberPlaceHolder'">Go!</button>
To change link use this:
document.querySelector('.start a').href = 'my-new-address'
Change your input type like this type="nummber" or type="text" for getting number or text only
<input required="required" onchange="getNumber()" id="cnt" type="nummber" placeholder="ISD">
<input required="required" onchange="getNumber()" id="wano" type="number" placeholder="Enter number">
You can add click event to your button like this.
function getNumber(){
document.getElementById("btngo").onclick = function() {
var ll = "myserver://sendphone="+document.getElementById('cnt').value+document.getElementById('wano').value;
console.log(ll); // checking url in console.
location.href = ll;
};
}

Disable textbox if other textbox is not empty in CSS and JavaScript

I have a search form which contains text-boxes. What I want to ask is if textbox1(Hotel (num_rooms)) is not empty then the textbox2(Packages(num_days)) will be disabled or if textbox2(Packages(num_days)) is not empty then the textbox1(Hotel (num_rooms)) will be disabled. Because this search form will leads to different output based on the inputs of an user. If the user tries to put data in textbox1 and submit it, then it will return a lot of recommendations based on the user preferences about hotel same as in packages.
<form action="Filtered-SearchResult.php" method="post">
<div class="SearchForm">
<label id="Form"><h3 style="color:beige; text-align:left;">Search Form</h3></label><br>
<br>
<input type="text" name="location" class="searchtext" id="locate" placeholder="location" onkeyup="LettersOnly(this)" /><br>
<input type="text" name="from_budget" class="searchtext" placeholder="minimum budget" style="width:150px;" onkeyup="NumbersOnly(this)" />
<input type="text" name="to_budget" class="searchtext" placeholder="maximum budget" style="width:150px;" onkeyup="NumbersOnly(this)" /><br>
<input type="text" name="person" class="searchtext" placeholder="no of person" onkeyup="NumbersOnly(this)" /><br>
<input type="text" name="no_of_rooms" class="searchtext" style="width:150px;" placeholder="hotel(num_rooms)" onkeyup="NumbersOnly(this)" />
<input type="text" name="no_of_days" class="searchtext" style="width:150px;" placeholder="Packages(num_days)" onkeyup="NumbersOnly(this)" />
<script>
function LettersOnly(input) {
var regex = /[^a-zA-Z ]/gi;
input.value = input.value.replace(regex, "");
}
function NumbersOnly(input) {
var regex1 = /[^0-9]/gi;
input.value = input.value.replace(regex1, "");
}
</script>
<input type="submit" name="search1" value="Show Prices" id="Prices2" />
</div>
</form>
You can write a change event for no of rooms and no of days like this.
You can add more condition accordingly
$("#no_of_days").change(function(){
if($(this).val() == ""){
$("#no_of_rooms").attr("disabled", false);
}else{
$("#no_of_rooms").attr("disabled", true);
}
});
$("#no_of_rooms").change(function(){
if($(this).val() == ""){
$("#no_of_days").attr("disabled", false);
}else{
$("#no_of_days").attr("disabled", true);
}
});

Type on textfield when it has focus using button Javascript

I have one button that displays number "1" when clicked and three text boxes. I want when the button is clicked the number is displayed on the text box that has focus. Can someone help me please.
function run(){
document.calc.txt1.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
t3">
When you click a button, the previous input looses focus. You could try to store the last focused input element before the click:
(this needs some more work)
var lastFocus = null;
document.addEventListener("blur", function(event) {
// Here, you'll need to find out if the blurred element
// was one of your valid inputs. It's probably best to
// identify them by a class name
if (event.target.type === "text") {
lastFocus = event.target;
}
}, true);
function run() {
// When the user hasn't yet focused on a text input,
// the first one is used by default
(lastFocus || document.calc.txt1).value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
var currId;
function setId(curr){
currId=curr.id;
}
function run(){
if(currId)
{
document.getElementById(currId).value +='1';
}
//document.calc.txt1.value += "1";
//document.activeElement.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1" onblur="setId(this)">
<input type="text" id="txt2" name="txt2" onblur="setId(this)">
<input type="text" id="txt3" name="txt3" onblur="setId(this)">
</form>
Ok, so this code snippet should do what you want. The main thing to note though is that whenever you click the button, the input box becomes blurred that you had selected.
Essentially what this code does here is set the onfocus attribute to allow you to figure out which input box was last focused, rather than which input box IS focused, because none are. Also, I'd recommend changing the button to a 'button' tag because it separates it in terms of tag name from the other input boxes.
Hope this helped, and let me know if you have any questions.
var inputs = document.getElementsByTagName('input');
for(var i = 1 ; i < inputs.length; i ++){
inputs[i].onfocus = function(){
this.setAttribute('class','focused');
}
}
function run(){
var inputBox = document.getElementsByClassName('focused')[0];
if(inputBox){
inputBox.value += "1";
inputBox.setAttribute('class','blurred');
}
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>

How can i change AlertBox into a div?

I would like to know how can I change the AlertBox into a div.
I want the alertBox message to appear next to the input but in a div.
Thank You.
This is my Form input code:
<form name="form" action="gigi.php" method="POST" onsubmit="return validateForm()">
<input type="hidden" name="action" value="submit">
First Name:<br>
<input name="name" type="text" size="30"/><br>
Last Name:<br />
<input name="lname" type="text" size="30"/><br>
Email:<br>
<input name="caca" type="text" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input class="submit" type="submit" value="Send email"/>
</form>
And this is First Name input code in JavaScript:
function validateForm(){
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
In your HTML add something like:
<div id="form-errors"></div>
Then in JS, you can do that:
var alertDiv = document.getElementById('form-errors');
if (!x || x == '') {
alertDiv.textContent = 'First name must be filled out!';
}
Readings:
textContent
Similar question
Your question is about forms ? Since HTML5 you can simply write required on the input tab and it won't validate until you write some data.. you can then sanitize it.
In addition to Ramy's response, you can add jquery hide/show effects to display and hide the div element.
Also, do not forget to add style "z-index" to the div, so that it will appear on above other content of web-page.

Categories

Resources