Prefill form fields with JSON url data - javascript

I just tried to (pre-)fill some form fields with JSON data, but it doesn't work.
This are my script and my form fields:
$(document).on('change', '#wf_id', function() {
$.getJSON("http://apis.is/horses?id=" + $("#wf_id").val(),
function(data) {
$.each(data.results[0], function(i, item) {
if (item == "name_and_origin") {
$("#wf_name_and_origin").val(item);
} else if (item == "ueln") {
$("#wf_ueln").val(item);
} else if (item == "date_of_birth") {
$("#datepicker_15").val(item);
} else if (item == "color_code") {
$("#wf_color_code").val(item);
} else if (item == "color") {
$("#wf_color").val(item);
} else if (item == "country_located") {
$("#wf_country_located").val(item);
} else if (item == "fate") {
$("#wf_fate").val(item);
} else if (item == "microchip") {
$("#wf_microchip").val(item);
} else if (item.father == "id") {
$("#wf_father_id").val(item);
} else if (item.father == "name_and_origin") {
$("#wf_father_name_and_origin").val(item);
} else if (item.mother == "id") {
$("#wf_mother_id").val(item);
} else if (item.mother == "name_and_origin") {
$("#wf_mother_name_and_origin").val(item);
}
});
});
});
<input type="text" name="fields[1]" id="wf_id" maxlength="150" value="" />
<input type="text" name="fields[2]" id="wf_name_and_origin" maxlength="150" value="" />
<select name="fields[25]" id="gender" size="1">
<option value="0" selected="selected">Bitte auswählen…</option>
<option value="1">Stute</option>
<option value="2">Hengst</option>
<option value="3">Wallach</option>
<option value="4">Geschl. unbekannt</option>
</select>
<input type="text" name="fields[14]" id="wf_ueln" maxlength="150" value="" />
<input type="text" class="datepicker" name="fields[15]" id="datepicker_15" maxlength="20" value="" />
<input type="text" name="fields[16]" id="wf_color_code" maxlength="150" value="" />
<input type="text" name="fields[17]" id="wf_color" maxlength="150" value="" />
<input type="text" name="fields[18]" id="wf_country_located" maxlength="150" value="" />
<input type="text" name="fields[19]" id="wf_fate" maxlength="150" value="" />
<input type="text" name="fields[20]" id="wf_microchip" maxlength="150" value="" />
<input type="text" name="fields[21]" id="wf_father_id" maxlength="150" value="" />
<input type="text" name="fields[22]" id="wf_father_name_and_origin" maxlength="150" value="" />
<input type="text" name="fields[23]" id="wf_mother_id" maxlength="150" value="" />
<input type="text" name="fields[24]" id="wf_mother_name_and_origin" maxlength="150" value="" />
The data from apis.is are like this:
{
"results":[
{
"id":"IS1987187700",
"name_and_origin":"Oddur frá Selfossi",
"ueln":"352002987187700",
"date_of_birth":"15.06.1987",
"color_code":"4521",
"color":"Palomino with a star flaxen mane and tail",
"country_located":"IS",
"fate":"Put down",
"microchip":null,
"father":{
"id":"IS1981157025",
"name_and_origin":"Kjarval frá Sauðárkróki"
},
"mother":{
"id":"IS1972287521",
"name_and_origin":"Leira frá Þingdal"
}
}
]
}
If I fill in a new value in wf_id the script seems to do "something" (think about asking apis.is...) but nothing I would like it else to do... ;)
I have no knowledge about debugging, so it is not easy to find out what's going wrong with this.

You need to understand what your KEYS and VALUES are.
I commented out the onChange on XHR call logic to just simply iterate over your provided data.
Edit
I created a second example below using a field mapping loop and function for extensibility and reusability.
var data = {
"results": [{
"id": "IS1987187700",
"name_and_origin": "Oddur frá Selfossi",
"ueln": "352002987187700",
"date_of_birth": "15.06.1987",
"color_code": "4521",
"color": "Palomino with a star flaxen mane and tail",
"country_located": "IS",
"fate": "Put down",
"microchip": null,
"father": {
"id": "IS1981157025",
"name_and_origin": "Kjarval frá Sauðárkróki"
},
"mother": {
"id": "IS1972287521",
"name_and_origin": "Leira frá Þingdal"
}
}]
};
//$(document).on('change', '#wf_id', function() {
// $.getJSON("http://apis.is/horses?id=" + $("#wf_id").val(), function(data) {
$.each(data.results[0], function(key, value) {
if (key === "name_and_origin") {
$("#wf_name_and_origin").val(value);
} else if (key === "ueln") {
$("#wf_ueln").val(value);
} else if (key === "date_of_birth") {
$("#datepicker_15").val(value);
} else if (key === "color_code") {
$("#wf_color_code").val(value);
} else if (key === "color") {
$("#wf_color").val(value);
} else if (key === "country_located") {
$("#wf_country_located").val(value);
} else if (key === "fate") {
$("#wf_fate").val(value);
} else if (key === "microchip") {
$("#wf_microchip").val(value);
} else if (key.father === "id") {
$("#wf_father_id").val(value);
} else if (key.father === "name_and_origin") {
$("#wf_father_name_and_origin").val(value);
} else if (key.mother === "id") {
$("#wf_mother_id").val(value);
} else if (key.mother === "name_and_origin") {
$("#wf_mother_name_and_origin").val(value);
}
});
// });
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="fields[1]" id="wf_id" maxlength="150" value="" />
<input type="text" name="fields[2]" id="wf_name_and_origin" maxlength="150" value="" />
<select name="fields[25]" id="gender" size="1">
<option value="0" selected="selected">Bitte auswählen…</option>
<option value="1">Stute</option>
<option value="2">Hengst</option>
<option value="3">Wallach</option>
<option value="4">Geschl. unbekannt</option>
</select>
<input type="text" name="fields[14]" id="wf_ueln" maxlength="150" value="" />
<input type="text" class="datepicker" name="fields[15]" id="datepicker_15" maxlength="20" value="" />
<input type="text" name="fields[16]" id="wf_color_code" maxlength="150" value="" />
<input type="text" name="fields[17]" id="wf_color" maxlength="150" value="" />
<input type="text" name="fields[18]" id="wf_country_located" maxlength="150" value="" />
<input type="text" name="fields[19]" id="wf_fate" maxlength="150" value="" />
<input type="text" name="fields[20]" id="wf_microchip" maxlength="150" value="" />
<input type="text" name="fields[21]" id="wf_father_id" maxlength="150" value="" />
<input type="text" name="fields[22]" id="wf_father_name_and_origin" maxlength="150" value="" />
<input type="text" name="fields[23]" id="wf_mother_id" maxlength="150" value="" />
<input type="text" name="fields[24]" id="wf_mother_name_and_origin" maxlength="150" value="" />
</form>
Version 2
You can create a mapping of keys to field ids. This way you can loop over any field.
var data = {
"results": [{
"id": "IS1987187700",
"name_and_origin": "Oddur frá Selfossi",
"ueln": "352002987187700",
"date_of_birth": "15.06.1987",
"color_code": "4521",
"color": "Palomino with a star flaxen mane and tail",
"country_located": "IS",
"fate": "Put down",
"microchip": null,
"father": {
"id": "IS1981157025",
"name_and_origin": "Kjarval frá Sauðárkróki"
},
"mother": {
"id": "IS1972287521",
"name_and_origin": "Leira frá Þingdal"
}
}]
};
// Map object keys to fields.
var keyToFieldMap = {
"name_and_origin" : "#wf_name_and_origin",
"ueln" : "#wf_ueln",
"date_of_birth" : "#datepicker_15",
"color_code" : "#wf_color_code",
"color" : "#wf_color",
"country_located" : "#wf_country_located",
"fate" : "#wf_fate",
"microchip" : "#wf_microchip",
"father" : {
"id" : "#wf_father_id",
"name_and_origin" : "#wf_father_name_and_origin"
},
"mother" : {
"id" : "#wf_mother_id",
"name_and_origin" : "#wf_mother_name_and_origin"
}
};
function isObject(val) {
if (val === null) { return false; }
return ((typeof val === 'function') || (typeof val === 'object'));
}
function populateFormFromData(data, mapping) {
$.each(data, function(key, value) {
var field = keyToFieldMap[key];
if (isObject(field)) {
$.each(value, function(subKey, subValue) {
$(field[subKey]).val(subValue);
});
} else {
$(field).val(value);
}
});
}
//$(document).on('change', '#wf_id', function() {
// $.getJSON("http://apis.is/horses?id=" + $("#wf_id").val(), function(data) {
populateFormFromData(data.results[0], keyToFieldMap);
// });
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="fields[1]" id="wf_id" maxlength="150" value="" />
<input type="text" name="fields[2]" id="wf_name_and_origin" maxlength="150" value="" />
<select name="fields[25]" id="gender" size="1">
<option value="0" selected="selected">Bitte auswählen…</option>
<option value="1">Stute</option>
<option value="2">Hengst</option>
<option value="3">Wallach</option>
<option value="4">Geschl. unbekannt</option>
</select>
<input type="text" name="fields[14]" id="wf_ueln" maxlength="150" value="" />
<input type="text" class="datepicker" name="fields[15]" id="datepicker_15" maxlength="20" value="" />
<input type="text" name="fields[16]" id="wf_color_code" maxlength="150" value="" />
<input type="text" name="fields[17]" id="wf_color" maxlength="150" value="" />
<input type="text" name="fields[18]" id="wf_country_located" maxlength="150" value="" />
<input type="text" name="fields[19]" id="wf_fate" maxlength="150" value="" />
<input type="text" name="fields[20]" id="wf_microchip" maxlength="150" value="" />
<input type="text" name="fields[21]" id="wf_father_id" maxlength="150" value="" />
<input type="text" name="fields[22]" id="wf_father_name_and_origin" maxlength="150" value="" />
<input type="text" name="fields[23]" id="wf_mother_id" maxlength="150" value="" />
<input type="text" name="fields[24]" id="wf_mother_name_and_origin" maxlength="150" value="" />
</form>

Related

enabled submit button if radio button field data and other field data found using jquery

I have few fields on this code snippet. Here I have radio button If Field_One is checked show mentioned input field (country select, first name, last name, mobile, email, trans id) same like if Field_Two is checked show mentioned field (reference no, id no and trans id)
Here Trans ID. First Name, Last Name is mandotory for both radio button and its a required field. But I have added few required field without last name.
And Field_Two radio field will show field like reference id and id no. I want if only one field is required field and if only one field is filled up then its ok from both reference id and id no.
But My code is not working properly See the below snippet
One thing if First Country is Africa then show another Dropdown box with Country2 but its also required when Africa is selected but Africa not selected its not required.
$(document).ready(function () {
function make_required_inputs(el) {
let value = el.val();
let div = $('div.' + value);
$('input[required]').removeAttr('required');
div.find('input.required').attr('required', true);
$('input[name="trxid"]').attr('required', true);
}
function validation() {
let valid = true;
$.each($('input[required]'), function () {
if ($(this).val() == '') valid = false;
});
if (valid) {
jQuery('#button1').attr('disabled', false);
} else {
jQuery('#button1').attr('disabled', true);
}
}
$('input[type="radio"]').click(function () {
if ($(this).attr("value") == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
$("#country").show();
}
if ($(this).attr("value") == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
$("#country").hide();
}
validation();
});
let checked = $('input[name="myfield"]:checked');
let value_checked = checked.attr("value");
if (value_checked == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
}else if (value_checked == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
}
$('input[type="radio"]')
make_required_inputs($('input[name="myfield"]:checked'));
$('input[name="myfield"]').on('change', function () {
make_required_inputs($(this));
validation();
});
$('input').keyup(function (e) {
validation();
});
jQuery("#country").change(function(){
jQuery(this).find("option:selected").each(function(){
var optionValue = jQuery(this).attr("value");
if(optionValue=='za'){
jQuery("#country2").show();
} else{
jQuery("#country2").hide();
}
});
}).change();
jQuery("#country2").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<br><br>
<select name="country" class="required" id="country">
<option>Select</option>
<option value="us">US</option>
<option value="uk">UK</option>
<option value="za">Africa</option>
</select>
<br><br>
<select name="country2" class="required" id="country2">
<option>Select</option>
<option value="eg">Egypt</option>
<option value="ng">Nigeria</option>
<option value="gh">Ghana</option>
<option value="za">South Africa</option>
</select>
<br><br>
<input type="text" name="first_name" class="required" placeholder="First Name" />
<br><br>
<input type="text" name="last_name" placeholder="Last Name"/>
<br><br>
<div class="Field_One">
<input type="text" name="mobile_no" placeholder="Mobile no"/>
<br><br>
<input type="text" class="required" name="email" placeholder="Email"/>
</div>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" class="required" placeholder="Reference no" /><br><br>
<input type="text" name="id_no" class="required" placeholder="ID no" />
</div><br>
<input type="text" name="trxid" class="required" placeholder="Trans ID" />
<input type="submit" id="button1" value="Submit" disabled/>
Update:
$(document).ready(function () {
function validation() {
let valid = true;
$.each($('input[required]:not([name="reference_no"],[name="id_no"]),select[required]'), function () {
if ($(this).val() == '') valid = false;
});
let one = 0;
if ($('input[one="true"][required]').length == 0) {
one = 1;
} else {
one = 0;
$.each($('input[one="true"][required]'), function () {
if ($(this).val() !== '') one++;
});
}
if (valid && one > 0) {
jQuery('#button1').prop('disabled', false);
} else {
jQuery('#button1').prop('disabled', true);
}
}
function required(value) {
$('input.required,select.required').prop('required', true);
if (value == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide().find('input,select').prop('required', false);
$("#country").show().addClass('required').prop('required', true);
}
if (value == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide().find('input,select').prop('required', false);
$("#country").hide().removeClass('required').prop('required', false);
jQuery("#country2").hide().removeClass('required').prop('required', false);
}
validation();
}
$('input[type="radio"]').click(function () {
required($(this).val());
});
let value_checked = $('input[name="myfield"]:checked').attr("value");
required(value_checked);
$('select,input').on('change keyup', function () {
validation();
});
jQuery("#country").change(function () {
var optionValue = jQuery(this).find("option:selected").attr("value");
if (optionValue == 'za') {
jQuery("#country2").show().addClass('required').prop('required', true);;
} else {
jQuery("#country2").hide().removeClass('required').prop('required', false);;
}
validation();
}).change();
jQuery("#country2").hide().removeClass('required').prop('required', false);
});
let valid2 = true;
$.each($('#domain_name,select[required]'), function () { if ($(this).val() == '') valid2 = false; }); if (valid2) { jQuery('#domsBtn').prop('disabled', false); } else { jQuery('#domsBtn').prop('disabled', true); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<br><br>
<select name="country" class="required" id="country">
<option value="">Select</option>
<option value="us">US</option>
<option value="uk">UK</option>
<option value="za">Africa</option>
</select>
<select name="country2" class="required" id="country2">
<option value="">Select</option>
<option value="eg">Egypt</option>
<option value="ng">Nigeria</option>
<option value="gh">Ghana</option>
<option value="za">South Africa</option>
</select>
<br><br>
<input type="text" name="first_name" class="required" placeholder="First Name" />
<br><br>
<input type="submit" id="firstCheck" value="First Name Check" disabled />
<br><br>
<input type="text" name="last_name" placeholder="Last Name" />
<br><br>
<div class="Field_One">
<input type="text" name="mobile_no" placeholder="Mobile no" />
<br><br>
<input type="text" class="required" name="email" placeholder="Email" />
</div>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" one="true" class="required" placeholder="Reference no" /><br><br>
<input type="text" name="id_no" one="true" class="required" placeholder="ID no" />
</div><br>
<input type="text" name="trxid" class="required" placeholder="Trans ID" />
<input type="submit" id="button1" value="Submit" disabled />

Javascript Validate Input fields + Select Field

I am using a very easy (but functional for my needs) Javascript script to validate input fields.
Here my main code:
<script language = "javascript">
function manage(txt) {
var bt = document.getElementById('send');
if (txt.value && txt2.value && txt3.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
Here are my fields
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onkeyup="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onkeyup="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onkeyup="manage(this)">
and here my Submit button:
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
What this does is to leave the submit button disabled until all fields have some value entered and works absolutely fine, however I also have a new and additional select option being:
<select name="Countries">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
......
</select>
I've tried to apply the following changes:
<script language = "javascript">
function manage(txt) {
var bt = document.getElementById('send');
if (txt.value && txt2.value && txt3.value && txt4.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
<select name="Countries" id="txt4" onkeyup="manage(this)">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
......
</select>
However it does not seem to work. Some expert advise would be greatly appreciated. Thank you very much.
The proper form is
if (txt.value!='' && txt2.value!='' && txt3.value!='' && txt4.value!='')
You don't want to set the onkyeup event, but onchange. More universal event is oninput.
You should also check the required form elements tag attribute, which can provide you similar functionality without javascript. See here.
First of all, listening keyup event on your select will work only in case if select was changed by the keyboard. In case if it was changed by mouse, your event won't be fired. Better to listen onchange
On another hand, you should check the emptiness of all text fields, as you do for txt4.value!='':
if (txt.value!='' && txt2.value!='' && txt3.value!='' && txt4.value!='') {
...
}
Now it will work.
function manage(txt) {
var bt = document.getElementById('send');
if ( txt.value != '' && txt2.value != '' && txt3.value != '' && txt4.value != '' ) {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onkeyup="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onkeyup="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onkeyup="manage(this)">
<select name="Countries" id="txt4" onchange="manage(this)">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
</select>
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
I have done this type of functionality before. So I'm sharing my code here.
HTML Code
<form method="Post" class="form">
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onblur="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onblur="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onblur="manage(this)">
<select name="Countries" id="txt4" onchange="manage(this)" class="input">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
</select>
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
</form>
Javascript Code:
<script>
function manage($e){
var input = document.getElementsByClassName("input");
var status=false;
for(var i=0;i<input.length;i++){
if(input[i].value.trim()!='' && input[i].value.trim()!=null && input[i].value.trim()!=undefined){
status = true;
} else {
status = false;
break;
}
}
console.log(status);
if(status===true){
var email = document.getElementById("txt3").value;
if(!(/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.trim()))){console.log('1');
document.getElementById('send').disabled = true;
} else {console.log('2');
document.getElementById('send').disabled = false;
}
} else {
document.getElementById('send').disabled = true;
}
}
</script>
There are many ways to resolve this type of functionality but for this case, I have used the above code to achieve the goal. If you have any queries, please let me know. Thanks.

javascript code when multiple checkboxes are checked form fields should appear according to the checkboxes(i tried this using select option method)

Need check-boxes instead of selection option and multiple check for check boxes according to the checked check boxes form fields should appear.
with a submit button. i have added css a small part, need a full detailed css for this case.
function showHide(elem) {
if(elem.selectedIndex != 0) {
//hide the divs
for(var i=0; i < divsO.length; i++) {
divsO[i].style.display = 'none';
}
//unhide the selected div
var y = document.getElementsByClassName('input'+elem.value);
for (var i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
window.onload=function() {
//get the divs to show/hide
divsO = document.getElementById("main-form").getElementsByTagName('input');
}
#main-form input {
display: none;
}
.common {
margin-bottom: 8px;
}
<head>
<title></title>
</head>
<body>
<form id="main-form">
<select onchange="showHide(this)" id="select-field">
<option value="">Select an option</option>
<option value="1">flight</option>
<option value="2">hotel</option>
<option value="3">travel</option>
</select>
<br><br>
<input type="text" class="input1 common" placeholder="flight">
<input type="text" class="input1 common" placeholder="flight2">
<input type="text" class="input1 common" placeholder="flight3">
<input type="text" class="input2 common" placeholder="hotel">
<input type="text" class="input2 common" placeholder="hotel2">
<input type="text" class="input3 common" placeholder="travel">
<input type="text" class="input3 common" placeholder="travel2">
<input type="text" class="input3 common" placeholder="travel3">
<input type="text" class="input3 common" placeholder="travel4">
</form>
<span id="show"></span>
Every time a checkbox is clicked, it triggers a toggle function which will either hide or show its corresponding textbox inputs.
function toggle(object){
var input;
var value = object.getAttribute("value");
switch(value){
case "flight":
input = "input1";
break;
case "hotel":
input = "input2";
break;
case "travel":
input = "input3";
break;
}
var elements = document.getElementsByClassName(input);
for(var i = 0; i < elements.length; i++){
if (elements[i].style.display == "block") {
elements[i].style.display = "none";
} else {
elements[i].style.display = "block";
}
}
document.getElementsByTagName("button")[0].style.display = "block";
}
.common {
margin-bottom: 8px;
}
input[type="text"]{
display:none;
}
button {
display:none;
}
<head>
<title></title>
</head>
<body>
<form id="main-form">
<input type="checkbox" onclick="toggle(this)" id="flight" value="flight"><label for="flight">Flight</label>
<input type="checkbox" onclick="toggle(this)" id="hotel" value="hotel"><label for="hotel">Hotel</label>
<input type="checkbox" onclick="toggle(this)" id="travel" value="travel"><label for="travel">Travel</label>
<br><br>
<input type="text" class="input1 common" placeholder="flight">
<input type="text" class="input1 common" placeholder="flight2">
<input type="text" class="input1 common" placeholder="flight3">
<input type="text" class="input2 common" placeholder="hotel">
<input type="text" class="input2 common" placeholder="hotel2">
<input type="text" class="input3 common" placeholder="travel">
<input type="text" class="input3 common" placeholder="travel2">
<input type="text" class="input3 common" placeholder="travel3">
<input type="text" class="input3 common" placeholder="travel4">
<button type="submit">Button</button>
</form>
<span id="show"></span>

I can not use two conditions in jQuery

I have a form like this:
<form>
<input type="radio" name="adsType" id="adsType" value="request" />
<input type="radio" name="adsType" id="adsType" value="provide" />
<select name="transactionType" id="transactionType">
<option value="1">Sale</option>
<option value="2">Rent</option>
</select>
<input type="text" name="price" id="price" />
<input type="text" name="min_price" id="price" />
<input type="text" name="max_price" id="max_price" />
<input type="text" name="fare" id="fare" />
<input type="text" name="min_fare" id="min_fare" />
<input type="text" name="max_fare" id="max_fare" />
</form>
I want:
when provide selected and click on Sale display price input only,
when provide selected and click on Rent display fare input only,
when request selected and click on Sale display min_price and max_price inputs,
when request selected and click on Rent display min_fare and max_fare inputs
i am trying for this javascript:
//<![CDATA[
$(function(){
$('input[name=adsType]').change(function () {
if ($(this).val() == 'provide') {
$('select[name=transactionType]').change(function () {
if ($(this).val() == '1') { /* Provide type | Sale type => display 'price' input only */
$('#price').show();
} else {
$('#price').hide();
}
if ($(this).val() == '2') { /* Provide type | Rent type => display 'fare' input only */
$('#fare').show();
} else {
$('#fare').hide();
}
});
}
if ($(this).val() == 'request') {
if ($(this).val() == '1') { /* Request type | Sale type => display 'min_price' and 'max_price' inputs */
$('#min_price').show();
$('#max_price').show();
} else {
$('#min_price').hide();
$('#max_price').hide();
}
if ($(this).val() == '2') { /* Request type | Rent type => display 'min_fare' and 'max_fare' inputs */
$('#min_fare').show();
$('#max_fare').show();
} else {
$('#min_fare').hide();
$('#max_fare').hide();
}
});
}
});
});//]]>
But it not return good result. Please help me to edit this JavaScript code!
I believe something like this may help. See the snippet and comments in the code:
$(function() {
function toggleFields() {
// setup which fields to show in every case
var items = {
provide: {
1: '#price',
2: '#fare'
},
request: {
1: '#min_price, #max_price',
2: '#min_fare, #max_fare'
}
}
// get the selected values
var ad = $('input[name="adsType"]:checked').val(),
tr = $('select[name="transactionType"]').val();
// hide all and show required
$('[id*="price"], [id*="fare"]').hide();
$(items[ad][tr]).show();
}
// handler for changes
$('select[name="transactionType"], input[name="adsType"]').change(toggleFields);
// initial run
toggleFields();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>request <input type="radio" name="adsType" value="request" checked/></label>
<label>provide <input type="radio" name="adsType" value="provide" /></label>
<select name="transactionType" id="transactionType">
<option value="1" selected>Sale</option>
<option value="2">Rent</option>
</select>
<div>
<label id="price">price <input type="text" name="price" /></label>
<label id="min_price">min_price <input type="text" name="min_price" /></label>
<label id="max_price">max_price <input type="text" name="max_price" /></label>
</div>
<div>
<label id="fare">fare <input type="text" name="fare" /></label>
<label id="min_fare">min_fare <input type="text" name="min_fare" /></label>
<label id="max_fare">max_fare <input type="text" name="max_fare" /></label>
</div>
</form>
TRY IT:
$(document).ready(function () {
var radioValue = "request";
var transactionValue = 1;
$('input[name=adsType]').change(function () {
radioValue = $(this).val();
update();
});
$('select[name=transactionType]').change(function () {
transactionValue = parseInt($(this).val(), 10);
update();
});
function update() {
if (radioValue === "provide") {
if (transactionValue === 1) {
$('#price').show();
$('#min_price').hide();
$('#max_price').hide();
$('#fare').hide();
$('#min_fare').hide();
$('#max_fare').hide();
} else {
$('#price').hide();
$('#min_price').hide();
$('#max_price').hide();
$('#fare').show();
$('#min_fare').hide();
$('#max_fare').hide();
}
} else {
if (transactionValue === 1) {
$('#price').hide();
$('#min_price').show();
$('#max_price').show();
$('#fare').hide();
$('#min_fare').hide();
$('#max_fare').hide();
} else {
$('#price').hide();
$('#min_price').hide();
$('#max_price').hide();
$('#fare').hide();
$('#min_fare').show();
$('#max_fare').show();
}
}
}
update();
});
FORM HTML > Please check form id: min_price
<form>
<input type="radio" name="adsType" id="adsType" value="request" checked="checked" />
<input type="radio" name="adsType" id="adsType" value="provide" />
<select name="transactionType" id="transactionType">
<option value="1" selected="selected">Sale</option>
<option value="2">Rent</option>
</select>
<input type="text" name="price" id="price" />
<input type="text" name="min_price" id="min_price" />
<input type="text" name="max_price" id="max_price" />
<input type="text" name="fare" id="fare" />
<input type="text" name="min_fare" id="min_fare" />
<input type="text" name="max_fare" id="max_fare" />
</form>
There is no onchange event for the select box inside the if ($(this).val() == 'request') { of your code.
I have made some changes like adding class all to the inputs #price #fare #max_price #max_fare #min_price #min_fare.
You can go through the code in the below snippet.
//<![CDATA[
$(function() {
$('input[name=adsType]').change(function() {
$('.all').hide();
$('#transactionType').val('');
if ($(this).val() == 'provide') {
$('select[name=transactionType]').change(function() {
$('.all').hide();
if ($(this).val() == '1') { /* Provide type | Sale type => display 'price' input only */
$('#price').show();
}
if ($(this).val() == '2') { /* Provide type | Rent type => display 'fare' input only */
$('#fare').show();
}
});
}
if ($(this).val() == 'request') {
$('select[name=transactionType]').change(function() {
$('.all').hide();
if ($(this).val() == '1') { /* Request type | Sale type => display 'min_price' and 'max_price' inputs */
$('#min_price, #max_price').show();
}
if ($(this).val() == '2') { /* Request type | Rent type => display 'min_fare' and 'max_fare' inputs */
$('#min_fare, #max_fare').show();
}
});
};
});
});
.all {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
request<input type="radio" name="adsType" id="adsType" value="request" /> provide
<input type="radio" name="adsType" id="adsType" value="provide" />
<select name="transactionType" id="transactionType">
<option value="" selected></option>
<option value="1">Sale</option>
<option value="2">Rent</option>
</select>
<input class='all' type="text" name="price" placeholder='price' id="price" />
<input class='all' type="text" name="min_price" placeholder='min_price' id="min_price" />
<input class='all' type="text" name="max_price" placeholder='max_price' id="max_price" />
<input class='all' type="text" name="fare" placeholder='fare' id="fare" />
<input class='all' type="text" name="min_fare" placeholder='min_fare' id="min_fare" />
<input class='all' type="text" name="max_fare" placeholder='max_fare' id="max_fare" />
</form>

javascript validate text box for numeric and string

I need some help with this javascript code. I want to validate Nights tax box and name text box, so they have a value in them. The Night text box must only accept a numeric number.
Here is my code
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
//var numeric = /^[0-9]+$/;
var regex = /[0-9]|\./;
$(":text, #error").after("<span>*</span>");
$("arrival_date").focus();
$(document).on("click", "#submit", function (e) {
var valid = true;
if ($("#name").val() === "") {
$("#name").next().text("This field is required.").css({
"color": "#FF0000",
"font-size": "13px"
});
valid = false;
}
else {
valid = true;
}
if ($("#nights").val() === "") {
valid = false;
$("#nights").next().text("This field is required.").css( {
"color": "#FF0000",
"font-size": "13px"
});
} else if (!regex.test("nights")) {
$("#nights").next().text("This field is required.").css( {
"color": "#FF0000",
"font-size": "13px"
});
valid = false;
}
else {
valid = true;
}
ad
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reservation request</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="reservation.js"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
UPDATED Code.
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
//var numeric = /^[0-9]+$/;
var regex = /[0-9]|\./;
$(":text, #error").after("<span>*</span>");
$("arrival_date").focus();
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$(document).on("click", "#submit", function (e) {
var valid = true;
if ($("#name").val() === "") {
$("#name").next().text("This field is required.").css({
"color": "#FF0000",
"font-size": "13px"
});
valid = false;
}
if ($("#nights").val() === "") {
valid = false;
$("#nights").next().text("This field is required.").css( {
"color": "#FF0000",
"font-size": "13px"
});
} else if (isNumeric("#nights")) {
$("#nights").next().text("This field is required.").css( {
"color": "#FF0000",
"font-size": "13px"
});
valid = false;
}
if (valid === false)
e.preventDefault();
}); });
I was hopping that someone could help me
You can use existing functions to check if an input is numeric (taken from here):
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
and you can use HTML5's input type number:
<input type="number" min="1" max="5">
Your current regex won't work since it will return true for any string that contains any kind of numbers, which is not the intended behavior.
Your usage of the variable valid is also incorrect: as your code is now, your form input will return as valid if #nights is properly validated - it will ignore the result of your name's input.

Categories

Resources