I am fairly new to JS, ive found a script which adds a text box below a select field when a specific option is selected (in this instance 'Other'), which works fine, although I want to have the option for the same box to appear if another option is selected aswell 'Friend'. How can I alter the part of the JS which determines this, from my understanding it is this part
function showfield(name){
if(name=='Other')
but i don't know the correct syntax to perform this. Im assuming effectively its something like
if(name=='Other' or 'Friend')
anyhelp would be highly appreciated, thank you.
Here is the current code.
<script type="text/javascript">
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="other" class="text-field" placeholder="Please state.." />';
else document.getElementById('div1').innerHTML='';
}
</script>
<form id="quote" class="quote-form">
<input name="" class="text-field" type="text" placeholder="Full Name" />
<input name="" class="text-field" type="text" placeholder="Contact Number" />
<input name="" class="text-field" type="text" placeholder="E-Mail Address" />
<select name="referral" class="select-field" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected">Where did you hear about us? (Please select..)</option>
<option value="Checkatrade">Check-a-Trade</option>
<option value="MyBuilder">MyBuilder</option>
<option value="Friend">Referral from a friend (Please state below)</option>
<option value="Other">Other (Please state below)</option>
</select>
<div id="div1"></div>
Like so:
if(name=='Other' || name=='Friend') {
//do stuff
}
The || operator in javascript is equivalent to the "or" you are attempting.
Read more on the available operators here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Operator_precedence
if(name=='Other' or 'Friend') is not correct.
you need to write the variable name a second time like this
if (name=='Other' || name=='Friend')
I know people have mixed feelings about switch statements, but in this case it works fairly well and is easier to adapt if you need to incorporate other option-specific changes.
switch (name) {
case "Other":
case "Friend":
//show input field
break;
default:
//hide input field
break;
}
Also, instead of creating and destroying the input element every time, it might be cleaner to just show and hide it with display: block and display: none
Related
How do I find the previous checkbox to an element using jquery?
I'm writing a custom validation plug-in "cb-required" which acts like "required" if and only if the previous checkbox is checked. The idea is a checkbox followed by one or more dependent text fields and/or selects. I'm not concerned with hiding or disabling the dependent fields in anyway, I just want to enforce "required" if the checkbox is checked.
Right now I'm simply trying to get an alert to pop-up correctly and .prev() is not doing the trick:
$.validator.addMethod("cb-required", function(value, element) {
alert("current="+$(element).attr("name")+" / previous="+$(element).prev(":checkbox").attr("name"));
return true;
}, "This information is required");
The form fields look something like this:
<input name="EMVEnabled" type="checkbox" value="1" />EMV enabled<br />
<span style="font-size:0.8em">
<strong>EMV Template</strong>
<select name="EMVTemplate" size="1" class="cb-required">
<option></option>
<option value="1">Template 1</option>
<option value="2">Template 2</option>
</select><br />
</span>
<br />
<input name="CashAdvance" type="checkbox" value="1" />Cash advance<br />
<br />
<input name="ExpressPay" type="checkbox" value="1" />Express pay<br />
<span style="font-size:0.8em">
<strong>Floor Limit Min</strong>
<input name="ExpressPayFloorMin" type="text" value="" size="12" maxlength="12" class="cb-required numeric" /><br />
<strong>Floor Limit Max</strong>
<input name="ExpressPayFloorMax" type="text" value="" size="12" maxlength="12" class="cb-required numeric" /><br />
</span>
Using your specific example, .prev(":checkbox") isn't working because that method does not move up the DOM treeāit will only look at direct siblings. You want to use .parent().prev(":checkbox") or parent.prevAll(":checkbox") if there is a chance that another DOM element would be between the checkbox and the dependent input's parent.
Alternatively, you may want to look into specifying, in your .validate({}) declaration for the "cb-required" rule, the exact checkbox (by jquery selector string) to use for validation, rather than relying on the structure of the DOM. This would give you the flexibility to place your checkbox anywhere in the DOM relative to the input(s) that depend on its checked state, like so:
$form.validate({
rules: {
ExpressPayFloorMin: {
"cb-required": "[name=ExpressPay]"
}
}
});
Using this method, you would need to add a third argument "param" to your validation function, which would be the selector specified in .validate():
$.validator.addMethod("cb-required", function(value, element, param) {
return $(param).prop("checked") && ($(element).val().length > 0);
}, "This information is required");
Believe it or not, your alternate method got me thinking of another way to tackle the problem. In the html I wrapped the checkbox and the dependencies in a div with class="cb-group" attribute. then the following tweak works:
$.validator.addMethod("cb-required", function(value, element) {
alert("current="+$(element).attr("name")+" / previous="+$(element).closest(".cb-group").find(":checkbox").attr("name"));
return true;
}, "This information is required");
Now I can continue and finish with the real logic. Thanks.
I am using a three part code below:
First part of the code: Basically a javascript function changeSearchEngine will be triggered when user select Google.
<p id="searchbox">This paragraph will change once javascript is triggered</p>
<form align=right>
<select name="searchengine" onchange="changeSearchEngine(this.form)">
<option value="google">Google</option>
</select>
</form>
This is my changeSearchEngine function in javascript.
function changeSearchEngine(form)
{
var searchEngine=form.searchengine.value;
if (searchEngine=="google")
{
var url_google='<form method="get" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="" /><input type="submit" value="Google Search"/></form>';
document.getElementById("searchbox").innerHTML=url_google;
}
}
At this point of time, all is working well. When I select Google, the searchbox for google appears. I can search and everything.
Notice there is a onsubmit="submitGoogle(this.form)" right? I need to save what the user search terms into SQL table. So I have this javascript function below to capture what user have type:
function submitGoogle(form)
{
alert("Inside submitGoogle function");
var searchterm=form.q.value;
alert(searchterm); //to test. this part didnt capture the value.
}
I managed to invoke the submitGoogle function BUT however I can't retrieve the value of q despite using searchterm=form.q.value. What did I do wrong here?
In your onsubmit handler, you are passing this.form. But, this already refers to the form since it is the form itself that triggers the submit event. Form fields have a form property, but the form itself does not have a form property. So, just change your handler to pass this instead of this.form.
http://jsfiddle.net/fmqNj/
onsubmit="submitGoogle(this)"
Okay I found one possible solution. Let me answer my own question.
In changeSearchEngine(form) function, i change to this:
var url_google='<form method="get" name="googleform" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="hello" /><input type="submit" value="Google Search"/></form>';
In submitGoogle(form) function, i change to this:
var searchterm=document.googleform.q.value;
But I still like others to comment on my solution whether it is not elegant or not within the practice. :D
I have a form with two inputs:
<input type="text" name="keyword" value="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" onfocus="wipe(this)"/>
and my JavaScript which gets rid of the pre-set value in form field as soon as you click it with your mouse is:
function wipe(obj)
{
obj.value="";
}
My question is, say the user doesn't type anything in the city field, how do I make it so that when the form is submitted the value for that field is empty and not the word City?
placeholder is a good attribute which can solve your problem its a past time history when we are used to using value for showing for which this textbox we have
<input type="text" name="keyword" placeholder="Search" />
if you still want to use java script modify your code something like this
<input type="text" name="keyword" value="Search" onfocus="wipe(this,'Search')" onblur="wipe2(this,'Search')"/>
<input type="text" name="city" value="City" onfocus="wipe(this,'City')" onblur="wipe2(this,'City')"/>
script function for second approch
function wipe(obj, str)
{
if(obj.value!=str){
obj.value="";}
}
function wipe2(obj, str)
{if(obj.value==""){
obj.value=str;}
}
You are using the wrong technique here. you should be using placeholder which is supported by most major browsers with the regular exception of IE. So if this is not a concern for you, you should definitely be using that. Especially, if you have a label element for that field. Otherwise you'd need to be checking for that input value on submission and see if it equals the string city
Just Declare a variable hasChanged and set it true when wipe function is called.Then call a function say 'SubmitFunction()'on the onclick function of Submit button.
<input type="text" name="keyword" value="Search" id="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" id="City" onfocus="wipe(this)"/>
<input type="submit" name="submit" value="submit" onclick="SubmitFunction();"/>
var hasChanged=false;
function wipe(obj)
{
hasChanged=true;
obj.value="";
}
function SubmitFunction()
{
if(hasChanged==false)
{
$("#City").val('');
}
}
at the time of submit why not check for value='city'
if(obj.value!='city')
{
//your code here
}
or if you have no problem in using jquery use watermark plugin this will handle browser compatibility problem also
Jquery Watermark
try this:
if($('input[name="city"]').val() && $('input[name="city"]').val() != 'city') { yourform.submit(); }
See How to prepopulate input text fields with prompting text which disappears on typing (jQuery) for some solutions to this. If you're okay with using HTML5, the best solution is probably to use "placeholder" instead of "value".
You should add one more attribute(eg. default <input type="text" name="keyword" default="Search" value="Search" onfocus="wipe(this)"/>) with value same as value attribute.
in on submit compare each form fields
function onSubmit(){
for (var fields in form)
if(form[fields].value== form[fields].getAttribute("default")){
form[fields].value = "";
}
}
}
I have a dynamic form that adds users to the site, made so you can duplicate the fields to add several users on one go.
So, my looks like
<input name="user[1][name]" value="" />
<input name="user[1][username]" value="" />
<input name="user[1][password]" value="" />
And then the number is changed on the duplicated fields, eg:
<input name="user[2][name]" value="" />
<input name="user[2][username]" value="" />
<input name="user[2][password]" value="" />
and so on.
On PHP I can handle each user since it has it's own array.
But I would like to validate, for example, the username on each user via jQuery.
The closest I got to is
$(this).find('input[name="user[][username]"]').each(function() {
But for it to work I need to explicitly write the number on the first [], eg:
$(this).find('input[name="user[1][username]"]').each(function() {
Is there a way to select ALL of them? I tried putting * and * between the [] but it didn't work.
Thanks for your help!
You can use the ends with selector
You could use a for loop and not have to write the numbers yourself really easily:
var number_of_forms = 3
for(var i=1;i<=number_of_forms;i++){
$(this).find('input[name="user[' + i + '][username]"]').each(function() {
}
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.
<form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />
<select id="choice1" name="choice1">
<option>Bye</option>
<option>Hello</option>
</select>
<select id="choice2" name="choice2">
<option>Bye</option>
<option>Hello</option>
</select>
<input type="submit" />
</form>
Look into,document.getElementsByTagName().
You really should use some javascript toolkit for help with this, but if not this might help:
validateSelectChoices = function(){
return document.getElementById('choice1').selectedIndex || document.getElementById('choice2').selectedIndex;
}
This will check to see if one of the select boxes has the 'hello' value selected (keep in mind that dropdowns will always default to the first option in the list, in your case 'bye'.
Have you tried the jQuery validation plugin?
You can see a demo here.