HTML Datalist value beside the option - javascript

I have two data list in the below snippet and the values of the selected option should be shown beside them.
My First(Account) one is working properly, but second(Head) one is not working. The value is not getting selected for Head.
/*List function starts*/
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
/*List function ends*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="accntid">Account: </label>
<input id="accntid" name="taccntlist" list="accnt_list" value="" placeholder="Account" required />
<datalist id="accnt_list">
<option data-value="001">Dummy1</option>
<option data-value="0000000">Dummy</option>
</datalist>
<input type="text" name="txtaccnt" id="accntid-hidden" readonly>
<br /><br /><br />
<label for="headid">Head: </label>
<input id="headid" name="txtheadlist" list="head_list" value="" placeholder="Head" required />
<datalist id="head_list">
<option data-value="1">d1</option>
<option data-value="0000000000">dummy</option>
</datalist>
<input type="text" name="txthead" id="headid-hidden" readonly>
<br /><br /><br />

I changed your js code, and added method forEach(), having previously declared the call to the inputs like this:
let inputs = document.querySelectorAll('input[list]');
This means that e.target is no longer necessary to use.
let inputs = document.querySelectorAll('input[list]');
inputs.forEach(function(current, index) {
current.addEventListener('input', function() {
list = current.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(current.getAttribute('id') + '-hidden'),
inputValue = current.value;
hiddenInput.value = inputValue;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="accntid">Account: </label>
<input id="accntid" name="taccntlist" list="accnt_list" value="" placeholder="Account" required />
<datalist id="accnt_list">
<option data-value="001">Dummy1</option>
<option data-value="0000000">Dummy</option>
</datalist>
<input type="text" name="txtaccnt" id="accntid-hidden" readonly>
<br /><br /><br />
<label for="headid">Head: </label>
<input id="headid" name="txtheadlist" list="head_list" value="" placeholder="Head" required />
<datalist id="head_list">
<option data-value="1">d1</option>
<option data-value="0000000000">dummy</option>
</datalist>
<input type="text" name="txthead" id="headid-hidden" readonly>
<br /><br /><br />

Related

Evaluate sum of values without clicking a button

I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.
However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).
I think change method can be used in the same manner.
#Edit:
Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with -566,2202888.
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
<input type="text" id="total" value="0" />
You can loop over all the <select> boxes and text inputs with:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
}
else if (this.id == "binayasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And if you change the checkboxes to use value instead of price, you can do them all in one loop:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text, #housepriceguesslist :checkbox:checked").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
else if (this.id == "binyasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And call the function when any of the inputs are changed:
$('#housepriceguesslist input, #housepriceguesslist select').change(calcAndShowTotal).change();
This solution is simple, just the get the list of all the inputs (i.e. checkbox, and dropdown) using the .find() method and the selector 'input:checkbox, input:text, select'. Then verify if each one of these inputs elements has the attribute checked or select for the checkbox and select input types respectively, or it is a multiplier for the text inputs. This verification ca be done inside of the each() method callback. Finally, just convert then the value to a number, using the parseFloat() method and add it to the total accumulator.
Finally, sum the value to the total input. Like this:
let container;
let inputs;
let total;
function calcAndShowTotal() {
let sum = 55435.04798; // it is constant value which must be the beginning value.
let value;
inputs.each(function() {
if ($(this).is('input:checkbox:checked')) {
// If is a checkbox
value = parseFloat($(this).attr('price')) || 0;
sum += value;
} else if ($(this).is('input:text:not(#total)')) {
// If is a text wait until you move to another element
let factor = 1;
if (this.id == 'm2') {
factor = 3134.204499;
} else if (this.id == 'binayasi') {
factor = -566.2202888;
}
value = parseFloat($(this).val()) * factor || 0;
sum += value;
} else if ($(this).is('select')) {
// If is a option from the select element
value = parseFloat($('option:selected', this).val()) || 0;
sum += value;
}
});
total.val(sum);
}
function initHandlers() {
inputs.on('keydown', function(e) {
let focusable, next;
if (e.keyCode == 13) {
focusable = inputs.filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
}
return false;
}
});
inputs.change(calcAndShowTotal);
calcAndShowTotal();
}
$(function() {
console.log('ready!');
total = $('#total');
container = $('#housepriceguesslist');
inputs = container.find('input:checkbox, input:text, select');
initHandlers();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
Total: <input type="text" id="total" value="0" />
<br/>
<br/>
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" />
Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
Note:
Remember to round the numbers to get more precision. The text modification will apply after you tab, or move to another element. So I added an enter listener so when you press enter is gonna move to the next element like when you press tab. Also, I moved the total to the top so you can see the results in the preview.
Update:
I recommend you to use the $(function(){}); to get the document when is ready. Inside you can assign the values of your elements. I notice that there was a bug in my code whenever ever you uncheck a checked element the Total should be 55435.04798, but it shows the double it is because total is also a text input.
Similar to Barmar's, I added all elements to the .each() loop but also added the .change() handler to all elements:
var context = $('#housepriceguesslist');
var elems = $('input:checkbox, input:text, select', context);
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
elems.each(function() {
if ( $(this).is('input:checkbox:checked') ) {
total += parseFloat($(this).attr('price')) || 0;
} else if ( $(this).is('#m2') ) {
total += parseFloat($(this).val()) * 3134.204499 || 0;
} else if ( $(this).is('#binayasi') ) {
total += parseFloat($(this).val()) * -566.2202888 || 0;
} else if ( $(this).is('select') ) {
total += parseFloat($('option:selected',this).val()) || 0;
}
});
$('#total').val(total);
}
elems.change(calcAndShowTotal); // handlers
calcAndShowTotal(); // first run
See example here: https://jsfiddle.net/qgvsern4/1/

How to include Array Elements in Drop Down Box

I have an array in Javascript that consists of three different countries. I have a form in my HTML page that contains a drop down box. Instead of populating the drop down box using
<option value=""> *option name* </option>,
I want to try including the elements of my array in my drop down box, so when the user clicks it, they'll see the elements.
var countries=["Sri Lanka","Bangladesh","India"]
I tried using the 'onclick' function in my HTML so that it would link to this following function
function myFunction() {document.getElementById('Bangladesh').innerhtml= (countries[2])>
But I since removed it since it didn't work. How exactly can I populate the drop down box with elements from my array. My JS and HTML code have been provided below.
<DOCTYPE html>
<head>
<script src="inquiries.js"> </script>
</head>
<body>
<h1 align="center"class='header1'> <font size="8"> </font> </h1>
<div class="busybox">
<form name="myForm" form action="/action_page.php" onsubmit="return validateForm();" method="post">
<label for="fname"> <b> First Name </b> </label>
<input type="text" id="fname" name="firstname" placeholder="Your name......"
required >
<label for="Birthday"> <b> E-Mail </b> </label>
<input type="text" id="email" name="email" placeholder="Enter your E-mail address....." >
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">
<option value="Sri Lanka"> Sri Lanka </option>
<option value="India"> India </option>
<option value="Bangladesh"> <p id="bangladesh"> </p> </option>
</select>
<label for="summary"> <b> Summary </b> </label>
<textarea id="summary" name="Summary" placeholder="Write a summary of your inquiry
here...." style="height:200px"> </textarea>
<input type="submit" value="submit" id="sbox" onclick="myfunction()">
</form>
----JS CODE----
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}else{
return true;
} }
var countries = ["Sri Lanka", "India", "Bangladesh"];
function myFunction() {document.getElementById('Bangladesh').innerhtml =(countries[2])>
var countries=["Sri Lanka","Bangladesh","India"];
document.getElementById("Select").innerHTML = "";
for(var i=0;i<countries.length;i++)
{
var node = document.createElement("option");
var textnode = document.createTextNode(countries[i]);
node.appendChild(textnode);
document.getElementById("Select").appendChild(node);
}
<select id="Select"></select>
Here is a solution using array#foreach.
var select = document.getElementById("selectCountry");
var countries = ["Sri Lanka", "India", "Bangladesh"];
countries.forEach((country) => {
var element = document.createElement("option");
element.textContent = country;
element.value = country;
select.appendChild(element);
});
<select id="selectCountry"></select>
Try this:
$('#country').change(function(){
var dropdown=document.createElement('select');
var options="";
for(i = 0; i < countries.length; i = i+1){
options+= "<option value='"+countries[i]+"'>"+countries[i]+"</option>";
}
dropdown.innerHTML= options;
document.getElementById('country').appendChild(dropdown);
});
To do it with jQuery:
$(document).ready(function() {
var select = $('#country');
var countries = ["Sri Lanka", "India", "Bangladesh"];
for (var i=0; i<countries.length; i++) {
var country = countries[i];
var el = $("<option value='" + country + "'>" + country + "</option>");
$(select).append(el);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">

javascript: submit button pulls all values from the textboxes and displays them in a p tag

So what I am trying to do here is when the submit button is clicked pull all of the values from the textboxes and display them in a p tag that I have on my html page. I have been tring to figure this out for days. Can somebody let me know what I am doing wrong?
/* JavaScript */
$("#submit").click(function(){
var doc = $("#doctorate").val()
var Name = $("#first_name").val();
var Last = $("#last_name").val();
var T = Doc + " "+ Name + " " + Last
break
var Certs = $("#certs").val()
break
var Title = $("#title").val()
break
var Department = $("#department").val()
break
var Numb = $("#number").val()
break
var Web = $("#website").val()
break
var Ema = $("#email").val()
document.getElementById('output').innerHTML = T;
})
HTML unchanged
The big problem I see is that you keep assigning the same thing to your output. Try something like this (reduced for brevity):
function myOut() {
var output = document.getElementById("certs").value;
output = output + document.getElementById("title").value;
if (certs != null) {
document.getElementById("output").innerHTML = output;
}
}
<input type="text" id="certs" />
<input type="text" id="title" />
<p id="output"></p>
<button onclick="myOut()">
Sub
</button>
Here you can try this one.
var role = document.getElementById("role").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var doctorate = document.getElementById("doctorate").value;
var certs = document.getElementById("certs").value;
var title = document.getElementById("title").value;
var department = document.getElementById("department").value;
var number = document.getElementById("number").value;
var website = document.getElementById("website").value;
var email = document.getElementById("email").value;
var output = document.getElementById("output").value;
$("#submit").click(function(){
var N = $("#first_name").val();
var L = $("#last_name").val();
var T = N + " " + L;
if (doctorate.checked) {
document.getElementById('output').innerHTML = T;
}
if (first_name != null) {
document.getElementById('output').innerHTML = T;
}
if (last_name != null) {
document.getElementById('output').innerHTML = T;
}
if (certs != null) {
document.getElementById('output').innerHTML = T;
}
if (title != null) {
document.getElementById('output').innerHTML = T;
}
if (department != null) {
document.getElementById('output').innerHTML = T;
}
if (number != null) {
document.getElementById('output').innerHTML = T;
}
if (website != null) {
document.getElementById('output').innerHTML = T;
}
if (email != null) {
document.getElementById('output').innerHTML = T;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset id="role">
<legend>My Role</legend>
<label for="faculty">
<input type="radio" name="role" id="faculty" value="faculty" />
Faculty
</label>
<label for="staff">
<input type="radio" name="role" id="staff" value="staff" />
Staff
</label>
</fieldset>
<fieldset id="userinformation">
<legend>User Information</legend>
<label for="doctorate">
Doctorate?
<input type ="checkbox" id="doctorate" value="" />
</label>
<label>
First Name:
<input type="text" name="name" id="first_name" required />
</label>
<label>
Last Name:
<input type="text" name="name" id="last_name" required />
</label>
<label>
Certifications:
<input type="text" name="cert" id="certs" />
</label>
<label>
Title:
<input type="text" name="title" id="title" required />
</label>
<label>
Department:
<select id="department" required>
<option disabled selected value>-Select a Department-</option>
<option>School of Information Technology</option>
<option>Mathematics</option>
<option>English</option>
<option>History</option>
<option>Natural Sciences</option>
<option>Psychology</option>
<option>School of Health Sciences</option>
</select>
</label>
<label>
Primary Phone #:
<input type="tel" name="number" id="number" placeholder="444-123-1234" pattern="^\d{3}-\d{3}-\d{4}$"/>
</label>
<label>
Email:
<input type="email" name="email" id="email" placeholder="JDoe#example.com" required />
<span id="err3"></span>
</label>
<label>
Website:
<input type="text" name="website" id="website" placeholder="http//:www.example" pattern="https?://.+" />
</label>
</fieldset>
<fieldset id = "results">
<p id="output"></p>
</fieldset>
<fieldset id="submit_button">
<input type="button" id="submit" value="submit" />
</fieldset>

how to bind URL param (key, values) to html fields dynamically using javascript

I have a URL, and html form like below, if any of the key matches to any of the field’s ID then bind value to that field.
I wrote below script, it is working fine when the field ids, param name are static.
How to bind the dynamic values to the associated dynamic fields by looping through the URL’s param (key, value) using JavaScript only.
var url = window.location.href;
var regex = new RegExp("[?&]msg(=([^&#]*)|&|#|$)");
var results = regex.exec(url);
document.getElementById("msg").innerHTML = !results ? "" : !results[2] ? "" : decodeURIComponent(results[2].replace(/\+/g, " "));
HTML form:
<input type="text" id="URL" value="http://xxxxz.com?email=bob#gmail.com&country=us&gender=male&msg=recordupdated" />
<label>Email:</label>
<input type="text" id="email" />
<label>Country:</label>
<select id="country">
<option value="ind">India</option>
<option value="us">USA</option>
</select>
<label>Gender:</label>
<input type="radio" name="gender" value="Male" />Male
<input type="radio" name="gender" value="Female" />Female
<span id="msg"></span>
<button type="submit">Submit</button>
You can try out this method : jsFiddle
This is with the assumption that the id or name of the element will be same as the parameter name in url.
function setValues() {
var s = document.getElementById("URL").value;
var queryString = s.split("?");
var params = queryString[1].split("&");
for (var i = 0; i < params.length; i++) {
var attribs = params[i].split("=");
if (attribs[0] === "msg") continue;
var elem = document.getElementById(attribs[0]);
var newVal = '';
if (elem) {
newVal = elem.value
} else {
elem = document.getElementsByName(attribs[0]);
for (var i = 0; i < elem.length; i++) {
if (elem[i].checked) {
newVal = elem[i].value;
}
}
}
params[i] = attribs[0] + "=" + (newVal == null ? '' : newVal);
}
document.getElementById("msg").innerHTML = queryString[0] + "?" + params.join("&");
}
<input type="text" id="URL" value="http://xxxxz.com?email=bob#gmail.com&country=us&gender=male&msg=recordupdated" style="width:100%;" />
<br/>
<label>Email:</label>
<input type="text" id="email" value="test#test.com" />
<label>Country:</label>
<select id="country">
<option value="ind">India</option>
<option value="us">USA</option>
</select>
<label>Gender:</label>
<input type="radio" name="gender" value="Male" />Male
<input type="radio" name="gender" value="Female" checked/>Female
<hr/>
<span id="msg"></span>
<hr/>
<button type="submit" onclick="setValues()">Submit</button>
P.S. : I know its bit lengthy and uses .split & for loops etc.. But i came up with this to keep the solution very simple. Suggestions to improve this are welcome :)

change input size depending on option selected

I've seen similar questions posted and tried to change them to meet my needs but I don't know enough about javascript to do it. All I want to do is limit a form input to 2 characters if they select "state" as their search option. This is what I have:
function changeValue(){
var option=document.getElementById('searchtype').id;
if (option == ("A") || ("B") ){
document.getElementById('field').size="40";
}
else if(option=="C"){
document.getElementById('field').size="2";
<form action="results.php" method="post">
Search By:<br />
<select id="searchtype" name="searchtype" onchange="changeValue();">
<option id="A" value="name">Hospital Name<br /></option>
<option id="B" value="city">City</option>
<option id="C" value="state">State</option>
</select>
<br /><br />
Search:<br />
<input id="field" name="searchterm" type="text" size="0">
Am I doing something wrong or is there a better way to do this?
I used Jack's code below and added a field.size attribute so my input matched the max allowed characters: (thanks Jack)
script type="text/javascript">
function changeValue(dropdown) {
var option = dropdown.options[dropdown.selectedIndex].value,
field = document.getElementById('field');
if (option == 'name' || option == 'city') {
field.maxLength = 40;
field.size = 40;
} else if (option == 'state') {
field.value = field.value.substr(0, 2);
field.maxLength = 2;
field.size = 2;
}
}
</script>
<h1>Hospital Search</h1>
<form action="results.php" method="post">
Search By:<br />
<select id="searchtype" name="searchtype" onchange="changeValue(this);">
<option id="name" value="name">Hospital Name<br /></option>
<option id="city" value="city">City</option>
<option id="state" value="state">State</option>
</select><br />
Search:<br />
<input id="field" name="field" type="text" size="40">
</input>
After deciding a dropdown with a list of states would be better, I changed it to this:
<form action="results.php" method="post">
Hospital Name:<br />
<input name="searchterm_name" type="text" size="40">
<br />
<input type="submit" name="submit" value="Search">
</form><br />
<form action="results.php" method="get">
City Name:<br />
<input name="searchterm_city" type="text" size="40"><br />
<select name="select_state">
<option value="">None
<option value="AL" Selected>Alabama
<option value="AK">Alaska
<option value="AZ">Arizona
</SELECT>
<input type="submit" name="submit" value="Search">
</form>
ED: Using form method "post" caused the browser to throw a warning every time I hit the back button to get to the results page. I changed to "get" since the information is not sensitive and now it goes back w/o warning.
Set the maxlength property:
document.getElementById('field').maxlength = 2;
I realize now that the rest of the code is not likely to work:
function changeValue(dropdown) {
var option = dropdown.options[dropdown.selectedIndex].value,
field = document.getElementById('field');
if (option == 'name' || option == 'city') {
field.maxLength = 40;
} else if (option == 'state') {
field.value = field.value.substr(0, 2); // before reducing the maxlength, make sure it contains at most two characters; you could also reset the value altogether
field.maxLength = 2;
}
}​
Then in your HTML:
<select id="searchtype" name="searchtype" onchange="changeValue(this);">
try this
function changeValue() {
var option2 = document.getElementById('searchtype').options[document.getElementById('searchtype').selectedIndex].id;
if (option2 == ("A") || option2 == ("B")) {
document.getElementById('field').size = "40";
}
else if (option2 == "C") {
document.getElementById('field').size = "2";
}
}​
Try this.
document.getElementById('field').setAttribute('size', "10");

Categories