Own defined attribute for input - javascript

I have a HTML File, that looks like this:
Input 1: <input type="text" required="false" /><br>
Input 2: <input type="text" required="true" /> *<br>
Input 3: <input type="text" required="false" /><br>
Input 4: <input type="text" required="false" /><br>
Input 5: <input type="text" required="true" /> *<br>
Input 6: <input type="text" required="false" /><br>
Input 7: <input type="text" required="true" /> *<br>
<input type="button" id="subButton" value="Run" />
This is my jQuery-script:
$(document).ready(function(){
$("#subButton").click(function(){
//Copy START
var setError = false;
$.each($(":input"), function(e){
if(($(this).attr("required") == "true") && (this.value == "")){
setError = true;
}
});
if(setError != false) alert("Not all required fields are filled");
//Copy END
});
});
If i change the attr to "type", it works if i not fill up every box. But i want to use this with the attribute required.
Any ideas, why it doesn't work?
Thanks for help

You are using required in a wrong way. If HTML, it should be this way:
<input type="text" required />
And if it is XHTML, it should be this way:
<input type="text" required="required" />
And you need to access it using jQuery using $.prop():
if($("input").prop("required")) { ... }
Else, you have the freedom to use data-* attributes this way:
data-reqd="yes"
And access it using:
if ($(this).data("reqd") == "yes") { ... }

use
data-required="true/false"
then
if ($(this).data("required")) ...

required is an official (not "own defined") attribute of <input>s, and it's boolean - "false" is an invalid value. Also, using jQuery's attr on this adds some additional quirks, so that you get back the string "required". Better use the required property, which really returns a boolean value.
Input 1: <input type="text" /><br>
Input 2: <input type="text" required /> *<br>
Input 3: <input type="text" /><br>
Input 4: <input type="text" /><br>
Input 5: <input type="text" required="" /> *<br>
Input 6: <input type="text" /><br>
Input 7: <input type="text" required="required" /> *<br>
<input type="button" id="subButton" value="Run" />
<script type="text/javascript">
$(document).ready(function(){
$("#subButton").click(function(){
var setError = false;
$(":input").each(function(e){
if ( this.required && this.value == "" )
setError = true;
}
});
if ( setError )
alert("Not all required fields are filled");
});
});
</script>

Related

compare the value of two form email fields

I have created a form requiring email validation. So user must type in their email address twice and if they don't match they won't be able to submit. I did this by simply comparing the values of email fields 1 and 2. If they match "disabled" is removed from the submit button.
All was working perfectly when I had the value set to "Insert your email address and "confirm your email address again". However, so that the user does not have to delete that text, I removed the value and used "placeholder" in the HTML instead.
The problem now is that the moment you type anything it's returning as true. I guess it's seeing the blank values as the same, but it's not picking up on the changes to the value as the user types it in.
Why are the two fields always returning as a match?
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses
Do Not Match">
</form>
<script>
function verify (){
console.log(`email1.value: ${email1}: Email2: ${email2}`);
if(document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
}
}
$(".fields").on("change paste keyup", verify);
</script>
</body>
</html>
try this
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="text" id="email1" class="fields" name="email" placeholder="Email Address" >
<input type="text" id="email2" class="fields" placeholder="Confirm Email Address" >
<input id="submit" type="button" onclick="verify()" value="click">
</form>
<script>
function verify()
{
if(document.getElementById("email1").value === document.getElementById("email2").value) {
alert("matched")
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
alert("not matched")
}
}
</script>
</body>
</html>
This worked for me:
Change the email inputs to [type='email'].
Add the required attribute to #email1.
Add a check to the validity of #email1 in your conditional.
Reset styles to initial (or what you prefer) if the button is reset back to 'disabled'.
Use 'input' event to get the the values updating on every keystroke, 'change' only fires on 'blur' or when the form is submitted.
It'd end up looking like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form class="theForm">
<p> Subscribe to my mailing list</p>
<input type="text" id="name" class="fields" name="name" placeholder="Name">
<input type="email" id="email1" class="fields" name="email" placeholder="Email Address" required>
<input type="email" id="email2" class="fields" placeholder="Confirm Email Address" >
<input name="submit" id="submit" class="fields" type="submit" disabled value="Email Addresses Do Not Match">
</form>
<script>
function verify (){
console.log(`email1: ${email1.value}: Email2: ${email2.value}`);
if(document.getElementById("email1").checkValidity() && document.getElementById("email1").value === document.getElementById("email2").value) {
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("submit").style.backgroundColor = "#004580";
document.getElementById("submit").style.cursor = "pointer";
} else {
document.getElementById("submit").setAttribute("disabled", "disabled");
document.getElementById("submit").style.backgroundColor = "initial";
document.getElementById("submit").style.cursor = "initial";
}
}
$(".theForm").on("input paste keyup", "input[type=email]", verify);
</script>
</body>
</html>
MDN Docs for input and change events:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Instead of:
$(".fields").on("change paste keyup", verify)
Try:
$(".fields").blur(verify)
EDIT:
How about:
$("#email2").blur(verify)
?

the function i set for my html button isn't working

i set a function for my button but the button doesn't follow it and it isn't being used anywhere else either
<div id="main2" class="main">
<form>
<label class="Courier" for="EventName"></label><br/>
<input class="Courier" required type="text" id="EventName" placeholder="Event name"><br/>
<input class="Courier" required type="Text" id="location" placeholder="venue"><br/>
<input class="Courier" required type="Text" id="DateAndTime" placeholder="Date and time"><br/>
<input class="Courier" required type="Text" id="Duration" placeholder="Duration"><br/>
<input class="courier" required type="Text" id="Clothing" placeholder="Dress code"><br/>
<input class="courier" required type="Text" id="Food" placeholder="Food"><br/>
<textarea class="courier" id="Notes" name="Notes" rows="4" cols="50">Enter additional notes here</textarea><br/>
<button id="submitEvent">Submit</button>
</form>
<br/>
<div id="newEvent"></div>
</div>
Javascript for the button below
$('#submitEvent').on('click' , function submitEvent(){
var event = $('#EventName');
var location = $('#location');
var DateAndTime = $('#DateAndTime');
var Duration = $('#Duration');
var Clothing = $('#Clothing');
var Food = $('#Food');
var Notes = $('#Notes');
var data ={
event: event,
location:location,
DateAndTime: DateAndTime,
Duration: Duration,
Clothing: Clothing,
Food: Food,
Notes: Notes
};
var eventRef = database.ref('Events');
var newEventRef = eventRef.push(data, function(err) {
if (err) {
console.error('Error Saving Data', err)
}
else{
console.log('success saving data');
$('#EventName').val('');
$('#location').val('');
$('#DateAndTime').val('');
$('#Duration').val('');
$('#Clothing').val('');
$('#Food').val('');
$('#Notes').val('');
}
})
})
i expect it to submit this to at least put on the console that the upload to firebase was successful or not but it doest do either it just refreshes my page to index.html and instead of the usual url it will be http://localhost:63342/Event%20Planner/www/index.html?Notes=1
when its usually
http://localhost:63342/Event%20Planner/www/index.html
Change this:
$('#submitEvent').on('click' , function submitEvent(){
to this:
$(document).on('click', '#submitEvent', function(){
I presume you are using .on() because the #submitEvent button is added dynamically. However, you must attach the .on event to an element that already exists when the DOM is initially rendered -- $(document) is a safe and common choice.
Reference:
Event delegation
I recommend you use the submit method https://api.jquery.com/submit/
<form id="yourFormName">
<label class="Courier" for="EventName"></label><br/>
<input class="Courier" required type="text" id="EventName" placeholder="Event name"><br/>
<input class="Courier" required type="Text" id="location" placeholder="venue"><br/>
<input class="Courier" required type="Text" id="DateAndTime" placeholder="Date and time"><br/>
<input class="Courier" required type="Text" id="Duration" placeholder="Duration"><br/>
<input class="courier" required type="Text" id="Clothing" placeholder="Dress code"><br/>
<input class="courier" required type="Text" id="Food" placeholder="Food"><br/>
<textarea class="courier" id="Notes" name="Notes" rows="4" cols="50">Enter additional notes here</textarea><br/>
<button type="submit">Submit</button>
</form>
And then
$( "#yourFormName").submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
Cheers!

Javascript, how to get multiple elements of a form and add an attribute to them?

<form name="myform">
<fieldset>
<legend>Delivery Information</legend>
<p>Country: <input pattern="^[A-Za-z]" type="text" name="textInput" size="25" placeholder="input country..."></p>
<p>Street: <input pattern="^[A-Za-z0-9]" type="text" name="street" size="30" placeholder="input street..."></p>
<p>City: <input pattern="^[A-Za-z ]" type="text" name="textInput" size="20" placeholder="input city..."></p>
<p>Zip: <input pattern="(\d{5}([\-]\d{4})?)" type="text" name="zip" size="5" placeholder="#####"></p>
</fieldset>
</form>
So, I have a form and I want to get all input elements by name "textInput"(I have other inputs so it ha) using Javascrip DOM, and add an attribute "oninvalid="please, only use letters".
Only Javascript, so no JQuery.
You can use this function:
function changeAttributes() {
var x = document.getElementsByName("textInput");
for(var i = 0; i < x.length, i++) {
x[i].setAttribute("oninvalid", "please, only use letters");
}
}
Try below:
$('input[name=textInput]').attr("oninvalid", "please, only use letters");

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

Show hidden input javascript/jquery

Why is the hidden form not shown when it looses focus? The alert is coming up nicely when leaving the input but the other hidden form is still not there.
html
<body>
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">
</body>
javascript
window.onload = function() {
$("#myinput").blur(myAlert);
};
function myAlert() {
alert("This input field has lost its focus.");
$("#validation_message_email").show();
}
You can't display a hidden input like that.A span will suit better for this purpose,
<input type="text" id="myinput" value="">
<span style="display:none" id="validation_message_email">enter a valid email</span>
validation_message_email doesn't have its display style property as none, so show() will not make it visible from type="hidden".
You need to replace
$("#validation_message_email").show();
with
$("#validation_message_email").attr( "type", "text" );
However, if the intent is to only show a message, then you don't need to use a hidden input for the same.
<body>
<input type="text" id="myinput" value="">
</body>
and
window.onload = function() {
$("#myinput").blur(function(){
alert("This input field has lost its focus.");
$(this).append('<span id="emailValidationMessage">enter a valid email</span>')
});
$("#myinput").focus(function(){
$("#emailValidationMessage").remove();
});
};
No need to use type="hidden" as hidden elements are not display:none they are hidden by default.
Use type="text" and hide it with css and show where you want
<input type="text" id="myinput" value="" style="display:none;">
use like this
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">
<script>
window.onload = function() {
$("#myinput").blur(myAlert);
};
function myAlert() {
$("#validation_message_email").attr("type","text");
}
</script>
<div class="form-group" id="usernamediv">
<input class="form-control" name="username" id="username"
placeholder="Username" type="text" required=""> </div>
<div class="form-group" id="passworddiv">
<input name="password" class="form-control" id="password" placeholder="Password" type="password" required="">
</div>
<button id="#loginButton">Login</button>
<button id="#forgotpassword">Forgot Password</button>
<script>
$("#forgotpassword").hide();
$("#forgotpassword").click(function(e){
$("#loginButton").hide();
$("#usernamediv").show();
$("#passworddiv").hide();
})
</script>
Check this jsfiddle link, it might help you.
$("#myinput").blur( function(){
myAlert();
});
function myAlert() {
$("#validation_message_email").attr("type", "text");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">

Categories

Resources