I have html running javascript after form,
form name="mortgage" method="post" action=" "onsubmit="return completeFormValidation();">
And javascript code for validation,
function completeFormValidation() {
location();
} // End of completeFormValidation
function location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
}
The code works perfectly fine in dream weaver but in browsers doesn't seem to work instead it will submit even if radio buttons aren't selected. Please help me out thanks.
because you are not returning the "FALSE/TRUE" value from completeFormValidation function.. And Change the name of the function Location is reserved by JavaScript.
check the jsfiddle
function completeFormValidation() {
return my_location();
}
its always better to return the value from location true OR false
you can modify your my_location() as below
function my_location(){
var numradio = document.mortgage.propLocation.length;
var selected="";
for(var i=0; i < numradio; i++){
if(document.mortgage.propLocation[i].checked == true){
selected += "Selected radio item " + i;
}
}
if(selected == ""){
document.getElementById("reserved").innerHTML = "<p> none radio selected </P>";
return false;
}
else{
return true;
}
}
try to replace
function completeFormValidation() {
location();
} // End of completeFormValidation
by
function completeFormValidation() {
return location();
} // End of completeFormValidation
Rename your location function. location is a native property of the window object and can not be redefined.
Related
I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating
Can someone help me out with validation of two text-box with same email Id.
I was able to pop an alert if both the text-box contain the same email Id via JavaScript(my requirement was both text-box cant have same email) but now I m facing a problem if second text box contain more then one email_Id separated my comma(,) the validation doesn't work.
I don't want email that is present in first text box repeat into second text-box.
My code:
<script language="javascript" type="text/javascript">
function validated() {
if (document.getElementById("<%=txtCountry.ClientID %>").value = document.getElementById("<%=txtnewViewer.ClientID %>").value) {
alert("Presenter cant be attende");
return false;
}Else{
return true;
}
}
</script>
check this code out
<script language="javascript" type="text/javascript">
function validated()
{
if (document.getElementById("<%=textbox1.id %>").value == document.getElementById("<%=textbox2.id %>").value)
{
alert("text-box cant have same email");
return false;
}
else
{
alert("Valid");
return true;
}
}
</script>
Can you try this.
var f_email = document.getElementById("f_email").value;
var s_email= document.getElementById("s_email").value;
if(f_email === s_email) {
// do something when email ids are same.
alert("email ids are same");
}
else {
// do something when email ids are same.
alert("email ids are not same");
}
First, you if statement contains an = who always return true and modify your variable (in place of ==).
function validated() {
var clientId = document.getElementById("<%=txtCountry.ClientID %>").value,
viewerId = document.getElementById("<%=txtnewViewer.ClientID %>").value;
if (clientId == viewerId) {
alert("Presenter cant be attende");
return false;
}
return true;
}
After that you can use : Array.indexOf():
var clients = clientId.split(","), viewers = viewerId.split(",");
// Here we have two arrays with all datas
for(var i = 0; i < clients.length; i++){
var k = viewers.indexOf(clients[i]);
if(k !== -1) {
alert(clients[i], "=", viewers[k]);
}
}
<body>
<input type="radio" name="other_charges" value="To Pay" >To Pay
<input type="radio" name="other_charges" value="COD" >COD
<input type="submit" onclick="sum_cash()"/>
</body>
here is my html ...in this i am having two radio buttons with different values and i have called a function using onclick event....here is the code...
<script type="text/javascript">
function sum_cash() {
var elements_ocharges = document.getElementsByName('other_charges');
for (var i = 0; i < elements_ocharges.length; i++) {
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if (val_ocharges=="To Pay") {
alert("pay");
}
if (val_ocharges=="COD") {
alert("cod");
}
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") ) {
alert("hi");
}
}
</script>
Now in the function, I am checking the value of the radio button selected. If the user chooses the Pay radio button then on clicking the submit button it alerts the user for payment. When the user chooses the COD radio button then on submitting it alerts COD.
What I want is that when the user has selected nothing and clicked on the submit button then it should alert the user. Unfortunately, it is not checking the condition. Can anyone please help me?
You may try like this:
<script type="text/javascript">
function sum_cash()
{
var elements_ocharges = document.getElementsByName('other_charges');
var value_ocharges = null;
for (var i = 0; i < elements_ocharges.length; i++)
{
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if(val_ocharges=="To Pay")
{
alert("pay");
}
else if(val_ocharges=="COD")
{
alert("cod");
}
else
{
alert("hi");
} }
</script>
your problem is this conditional near the top:
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
since neither radio button is checked, value_ocharges is never set. this will cause an error when you attempt to access the value with var val_ocharges=value_ocharges; you should set the value of value_ocharges to something (null is fine) before entering your loop, then everything will work:
<script type="text/javascript">
function sum_cash()
{
var elements_ocharges = document.getElementsByName('other_charges');
var value_ocharges = null;
for (var i = 0; i < elements_ocharges.length; i++)
{
if (elements_ocharges[i].checked)
value_ocharges = elements_ocharges[i].value;
}
var val_ocharges=value_ocharges;
if(val_ocharges=="To Pay")
{
alert("pay");
}
if(val_ocharges=="COD")
{
alert("cod");
}
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") )
{
alert("hi");
}
}
</script>
Try this ,
else if ((val_ocharges =="")
{
alert("hi");
}
Hope this helps!!
First, set your value_ocharges above the for loop:
var value_ocharges = false;
Then, instead of:
if ((val_ocharges!="COD") && (val_ocharges!="To Pay") ) {
alert("hi");
}
use this outside of the loop:
if (!val_ocharges){
alert("hi");
}
Basically, this checks if val_ocharges is defined somewhere in the loop, and if it's not, it triggers the alert.
I would like to put the following in a for loop but i am having difficulties. Any help would be appreciated
$("input:submit").click(function(){
if (!$("input[name=attendance1]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance2]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance3]").is(":checked")) {
alert('Please select preference');
return false;
}
});
});
I have tried:
for($i=1; $i<=3; $i++)
{
$("input:submit").click(function(){
if (!$("#food" + $i).is(":checked")) {
alert('Please select preference');
return false;
}
});
});
First fix:
alert('Please select preference);
with
alert('Please select preference');
Then if you want to loop:
for (var i = 0; i < 3; i++) {
if (!$("input[name=attendance" + i + "]").is(":checked")) {
alert('Please select preference');
return false;
}
}
Or better yet use jQuery's startsWith selector:
if (!$('input[name^="attendance"]').is(":checked")) {
alert('Please select preference');
return false;
}
Example
You're missing a closing single quotation mark on all 3 alert statements.
I generally use a class name on my DOM elements when I want to do something like this. That makes it easier to iterate through the elements using .each(). I was not aware of the startsWith selector mentioned above, but it does look a bit cleaner than my method.
<!-- DO STUFF -->
<input name="attendance1" class="my-unique-class-name" />
<input name="attendance2" class="my-unique-class-name" />
<input name="attendance3" class="my-unique-class-name" />
<!-- DO STUFF -->
<script type="text/javascript">
$("input:submit").click(function(){
var valid = true;
$("input.my-unique-class-name").each(function (el) {
if ( ! $(el).is(":checked") ) {
valid = false;
}
});
if ( ! valid ) {
alert('Please select preference');
return false;
}
});
</script>
Here's my take on it. it has the advantage of you listing down in an array what names you want checked, regardless what names they are
//jQuery '.on()' for versions 1.7+
$("input:submit").on('click', function() {
//assume valid unless found otherwise
var valid = true;
//add the input names you want to verify
var nameList = [
'attendance1',
'attendance2',
'attendance3'
];
//loop through names
for (var i = 0; i < nameList.length; i++) {
var checked = $('input[name="'+nameList[i]+'"]').is(':checked');
if (!checked) {
alert('Please select a preference');
//mark false when something wrong found
valid = false;
}
}
//check if validity persisted
if(valid){
//do something
}
//prevent default actions
return false;
});
I have a problem, i have X <input type="checkbox" /> in my code, now I want to foreach this object/array its out put. - look my code.
$("#denied_seekrs").click(function()
{
if (!isCheckedById("selectname"))
{
alert ("Please select at least one event");
return false;
}
else
{
alert( $("input[#id=selectname]:checked").val() ); //submit the form
}
});
function isCheckedById(id)
{
var checked = $("input[#id="+id+"]:checked").length;
if (checked == 0)
{
return false;
}
else
{
return true;
}
}
When I output it in alert i get a object, but if I have select 2 checkbox I what the value in this 2 checkboxes.
I hope I can be helpful and all here understand me :)
How about
$("#denied_seekrs").click(function() {
var checkedInputs = $("input:checked");
var test = "";
$.each(checkedInputs, function(i, val) {
test += val.value+",";
});
test = test.substring(0,(test.length-1));
alert(test);
});
I'm not exactly sure what you're looking for, but I'm guessing that the jQuery.each() method will help. You can use it to iterate over arrays, objects, and more.
var arr = [ "one", "two", "three", "four", "five" ];
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
how about something like this:
jQuery.each(checked, function() {
$(checked + this).text("My id is " + this + ".");
});
Can it be that - ultimately - you are looking for $.serializeArray() or $.serialize()?
If not, then maybe this is helps you:
$("#denied_seekrs").click(function()
{
if (!isCheckedById("selectname"))
{
alert ("Please select at least one event");
return false;
}
else
{
// prepare array of values
var values = [];
// prepare list of checked checkboxes
var $checkboxes = $("input[#id=selectname]:checked");
// push each individual value into the array
$checkboxes.each(function() { values.push( $(this).val() ); });
// debug output
alert( values.join("\n") );
//submit the form
}
});
When I got you right, you want the user to select one checkbox (or is it one or more?). This should do it:
$("#denied_seekrs").click(function()
{
var $checkedInputs = $("input:checked");
if ($checkedInputs.length != 1)
{
alert ("Please select one event");
return false;
}
alert( $checkedInputs.val() ); //submit the form
});
EDIT:
After reading your question again, I realized that the above code does not answer your question. However, the above does work and is a much shorter version of your solution. Maybe you want to use it instead. To answer your question, you could alert the value of all checked boxes like this:
Change this:
alert( $checkedInputs.val() ); //submit the form
to this:
var values = "";
$checkedInputs.each(function(){
values += $(this).val() + " ";
});
alert( values );