Unable to manipulate DOM element with jQuery - javascript

I've run into a very strange situation. I have a simple registration form which has an input box to validate a registration. The whole site is essentially one large stylized form. In my mockup (CodePen demo), everything works fine. If the key matches, the input background is shaded green.
HTML
<div id="workshops">
<h1>Upcoming Workshops</h1>
<p>To register for a workshop, fill in your name information and then click on the button next to each session title. Click <b>Register</b> when you're finished.</p>
<div id="form">
<form id="classSignup" class="noSubmit" onsubmit="handleFormSubmit(this)">
<input id="email" name="email" type="hidden" value="<?= Session.getActiveUser().getEmail(); ?>" />
<input id="first" name="first" type="text" onfocus="this.value=''" value="First Name" required />
<input id="last" name="last" type="text" onfocus="this.value=''" value="Last Name" required />
<select id="bldg" name="building"></select>
<input type="submit" value="Register" />
<div id="list">
<div class='row' id='row9'>
<span class='time'>8:00</span>
<span class='date'>6/20/2017</span>
<input type='checkbox' name='wkshp' value='6/20/2017'/>
<span class='title'>
<label for='wkshp'>Demo workshop</label>
</span>
<span class='desc'>This is the class description</span>
<div class='meta'>
<span class='loc'>Admin building</span> |
<span class='cat'>1a, 2b, 2c, 3d</span> |
<span class='type'>Online</span> |
<span class='seats'>Seats: 15</span>
</div>
<label>
<input type='text' class='lock' name='regCode9' value='Code' />
</label>
</div>
</div>
</form>
</div>
</div>
Example Script
$("div.lock").keyup(function() {
if( $(this).val() == "abc") {
$(this).css('background-color', 'rgba(0, 255,0,0.4)')
} else {
$(this).css('background-color', 'white')
}
})
When I move this over to my live site, I can't access the input element with jQuery. I can find it in the DOM and edit CSS in the Inspector, but regardless of what I do, I can't even get an error message to log in the console. I have plenty of other scripts running with no problems on the page.
I'm really at a loss as to why it works in one site but not another. Any ideas are appreciated.

Try delegating the keyup event
$("body").on("keyup","input.lock", function() {
if( $(this).val() == "abc") {
$(this).css('background-color', 'rgba(0, 255,0,0.4)');
} else {
$(this).css('background-color', 'white');
}
});

Related

addEventListener for input not working anymore after validation error is thrown

The problem
I use a form on a webpage where users fill in all sorts of details. There are 3 fields which generate the input for another field. That field gets generated like this: Firstname + Lastname + Date of birth. However, when a validation error is thrown on the form and the page reloads, the generated input isn't the expected format anymore. Only the Date of birth is then in that input.
It looks like it isn't initializing the Firstname + Lastname field anymore after a validation error is thrown on the page. Any suggestions on how to make it so that the fields gets initialized constantly? Or is there maybe a better way to handle this?
This is the code I use for the generated input
window.onload = function() {
let studentNoField = document.getElementById('input_7_9');
let enteredDetails = {
name: '',
lastname: '',
date: ''
};
/* set value in the third input: Studentnummer */
function generateInput() {
let studentNumber = Object.values(enteredDetails).join('').toLowerCase();
studentNoField.value = studentNumber;
}
/* event listener for first input: Voornaam */
document.getElementById('input_7_1').addEventListener('input', function(event) {
enteredDetails.name = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Achternaam */
document.getElementById('input_7_25').addEventListener('input', function(event) {
enteredDetails.lastname = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('input', function(event) {
enteredDetails.date = event.target.value.replace(/-/g, '').slice(0, 4);
generateInput();
});
/* Get selected training and format it properly for the PDF */
jQuery('#input_7_23').change(function(e) {
var optionChange = jQuery('#input_7_23 option:selected').text().toUpperCase();
jQuery('#input_7_58').val(optionChange);
});
}
<html>
<body>
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen" onclick="if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; jQuery("#gform_7").trigger("submit",[true]); }">
</div>
</form>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Any help or suggestions is appreciated.
There were a few non-existing ids referenced in your code. In the following snippet I have tried to "correct" these errors, but I also went further: I removed all repetitions, thereby following the DRY principle "Don't repeat yourself". The "input"-event listener now works for all elements of the inps array. There is, however one differentiation: the first two elements are limited to 8 characters while the date is limited to 4: .slice(0,i<2?8:4).
const [stNr, ...inps]=[9, 1, 25, 3].map(n=> document.getElementById(`input_7_${n}`));
inps.forEach(inp=>inp.addEventListener("input",()=>
stNr.value=inps.map((el,i)=>
el.value.replace(/[\s-]/g,"").slice(0,i<2?8:4).toLowerCase()
).join(""))
)
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer</label>
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen">
</div>
</form>
I removed your jQuery statements at the end of your script, as they referred to non-existent ids. These statements can definitely also be re-written in Vanilla JS, if necessary.
And, as #CherryDT already mentioned: there is no validation code visible here. If it happens on the server then it is the server's responsibility to produce a suitable response that allows the client to render the page with the previously (possibly annotated) content.

Custom javascript to check if fields are required

I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value)
alert(field.name + ' is required');
});
console.log(fields);
}
</script>
If anyone can work out how to include validation of check boxes, it would be much appreciated.
Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name">
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
$.each(fields, function(i, field) {
field=$(field).find('input, select, textarea')[0]
if (!field.value || (field.type=='checkbox' && !field.checked))
alert(field.name + ' is required');
});
}
</script>
The problems were:
serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
Checkboxes don't have a property value, instead they are checked
There is more than one way to determine this:
Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:
if($("input[name='Check_0']:checked").length === 1)
Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.
if(!$("input[type='checkbox']")[0].checked)
NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you
should always do a second round of validation on the server that will
be receiving the data.
FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="userName" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
alert(field.name + ' is required');
}
});
// Check to see if the input is a checkbox and if it's checked
if(!$("input[type='checkbox']")[0].checked){
alert("You must agree to the terms to continue.");
}
}
</script>
Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.
Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.
If you're interested, here's your code without JQuery:
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="name" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
// Get all the required elements into an Array
var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
// Loop over the array:
fields.forEach(function(field) {
// Check for text boxes or textareas that have no value
if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
&& !field.value){
alert(field.name + ' is required');
// Then check for checkboxes that aren't checked
} else if(field.type === "checkbox" && !field.checked){
alert("You must agree to the terms to continue.");
}
});
}
</script>

Hide element on uncheck

I have a checkbox pre-selected saying "Use profile address" and address is showing below.
Now what I want is if a customer unchecks the checkbox the pre-shown address gets hidden and a new input saying add different address appears.
I tried to do this using this JS trick. But couldn't achieve what I wanted. Can someone help?
$('#address-checked').change(function(){
if (this.checked) {
$('#address-sh').fadeIn('slow');
} else {
$('#address-sh').fadeOut('slow');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="address-checked" checked="checked" class="mb-3">
<label class="car-list-step-equipment-label">Use profile address</label>
<address> 9 Longacre Road<br />London, GB, E17 4DT</address>
<div id="address-sh">
<input type="text" />
</div>
You were simply hiding/showing the wrong HTML element. Changing the selector to just the address element fixes the issue. But, going a bit further, if you initialize the textbox and its label so that they are hidden at the start, then you don't need an if/else statement at all. You can just toggle the address and the textbox when the checkbox gets checked.
$('#address-checked').on("change", function(){
// You don't need and if/then here. Just toggle the visibility
$('address').toggle('slow');
$('.hidden').toggle('slow');
});
.hidden { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="address-checked" checked="checked" class="mb-3">
<label class="car-list-step-equipment-label">Use profile address</label>
<address>
9 Longacre Road<br>
London, GB, E17 4DT
</address>
<div id="address-sh" class="hidden">
<label>Enter new address: <input type="text"></label>
</div>
Additionally, JQuery no longer recommends the use of shortcut event methods, such as change. Instead, the recommend the on() method, that you pass the event name to.
Lastly (FYI), don't self-terminate your HTML tags. That's a left over syntax from the days of XHTML and really serves no purpose today. In fact, using that syntax can actually introduce bugs into your code. Read this for details.
and a new input saying add different address appears.
Add this new input and toggle the display basing on the check/uncheck performed by the user:
$('#address-checked').change(function() {
$('#address-sh').toggle(!this.checked);
$('address').toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="address-checked" checked="checked" class="mb-3">
<label class="car-list-step-equipment-label">Use profile address</label>
<address>9 Longacre Road<br />London, GB, E17 4DT</address>
<div id="address-sh" style="display: none">
Enter new address: <input type="text" />
</div>
You have given id to input type text div and you are trying address label
$('#address-checked').change(function(){
if ($(this).is(':checked')) {
$('#address').fadeIn('slow');
$('#address-sh').fadeOut('slow');
} else {
$('#address').fadeOut('slow');
$('#address-sh').fadeIn('slow');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="address-checked" checked="checked">
<label class="car-list-step-equipment-label">Use profile address</label>
<address id="address">
9 Longacre Road<br />
London, GB, E17 4DT
</address>
<div id="address-sh" style="display:none;">
<input type="text" />
</div>

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

How to disable form submit button if text field value is set to a specific value or blank?

I've created a form using Google Docs which sends data to a google spreadsheet. I've taken the html code and reformatted it to my css/style and it works perfectly. It also displays a custom thankyou page and the only problem I'm facing is that it doesn't validate the data.
So, I'm thinking of disabling the submit button if the user hasn't entered anything in the required fields. Or, you could suggest a way to prevent blank form submission?
Currently My form has 2 text fields, and 4 checkboxes. I require both the text fields, but not the checkboxes. The text fields are currently populated/cleared with html/script:
value="Your Email or Phone No."
onfocus="if (this.value=='Your Email or Phone No.') this.value='';"
I require my form to disable the submit button if no data has been entered.
Here's my full code:
<script type="text/javascript">var submitted=false;</script>
<iframe name="hidden_iframe" id="hidden_iframe" style="display:none;" onload="if(submitted) {window.location='thankyou.htm';}"></iframe>
<form action="Google_Form_ID_Here_(removed-for-stackoverflow-post)" method="POST" target="hidden_iframe" onsubmit="submitted=true;">
<ol style="padding-left: 0">
<div dir="ltr"><label for="entry_145">Name
<label for="itemView.getDomIdToLabel()" aria-label="(Required field)"></label>
</label>
<input type="text" name="entry.145" value="Enter Full Name" id="entry_145" dir="auto" aria-required="true" onfocus="if (this.value=='Enter Full Name') this.value='';">
</div>
<div dir="ltr" ><label for="entry_624">Contact Info
<label for="itemView.getDomIdToLabel()" aria-label="(Required field)"></label>
</label>
<input type="text" name="entry.624" value="Your Email or Phone No." id="entry_624" dir="auto" aria-required="true" onfocus="if (this.value=='Your Email or Phone No.') this.value='';">
</div>
<div align="center">
<div dir="ltr"><label for="entry_755"><br>Checkboxes
</div><br>
<div dir="ltr">Check which of the functions you'll be attending.</label><br><br>
<table align="center" width="248" height="128" border="0">
<span>
<tr>
<td align="center"><input id="group_418_1" name="entry.418" type="checkbox" value="Event 1"/>
<label class="vis_hide">Event 1</label></td>
<td align="center"><input id="group_418_2" name="entry.418" type="checkbox" value="Event 2"/>
<label class="vis_hide">Event 2</label></td>
<td align="center"><input id="group_418_3" name="entry.418" type="checkbox" value="Event 3"/>
<label class="vis_hide">Event 3</label></td>
<td align="center"><input id="group_418_4" name="entry.418" type="checkbox" value="Event 4"/>
<label class="vis_hide">Event 4</label></td>
</tr>
</span>
</table>
<input type="hidden" name="draftResponse" value="[]">
<input type="hidden" name="pageHistory" value="0">
<div dir="ltr">
<input type="submit" name="submit" value="Confirm" class="sbutton">
</div></ol></form>
Please can someone provide help regarding this? Or a suggestion for alternative to prevent blank submissions or provide a link to the solution? Can this be done with some jquery script too?
Thanks for any help.
EDIT:
I tried this script but that didn't help too...
<script>
$(function () {
// give the <form> the ID "myform" (or whatever you want) before using this code!
var form = $("#myform");
var input1 = $("#entry_145"); //for name
var input2 = $("#entry_624"); //for contact
form.addEventListener("submit", function (evt) {
if (input1.val() == "" || input2.val() == "") {
evt.preventDefault();
}
}, false);
});
</script>
Use it or leave it ,Dirty code
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<input type="text" class="req" id="name" />
<input type="text" class="req" id="post" />
<input type="submit" class="btn" id="button" onClick='alert("hi");' disabled/>
<script>
$(function (){
$('.req').change(function(){
if ($('#name').val() == '' || $('#post').val() == '')
{
$('#button').attr('disabled',true);
}
else
{
$('#button').attr('disabled',false);
}
});
});
</script>
There are two ways for client-side "validation":
Use JavaScript and add a submit event listener to your <form> tag.
Add the required attributes to your text boxes:
<input type="text" required="required" />
But these won't prevent users with an old browser (when using second option) or computer savvy people who just send the form manually.
You have to perform server-side validation, too!
Try this for the change event listeners:
$(function () {
// give the <form> the ID "myform" (or whatever you want) before using this code!
var form = $("#myform");
var input1 = $("#my-input1-name");
var input2 = $("#my-input2-name");
form.submit(function (evt) {
if (input1.val() == "" || input2.val() == "") {
evt.preventDefault();
}
});
});

Categories