How to take values from multiple options of select input field - javascript

My code is:
<form method="post">
<select name="item" multiple>
<option value="1">Lotus</option>
<option value="2">Sun Flower</option>
<option value="3">MNC</option>
<option value="4">DELL</option>
<option value="5">LENOVO</option>
</select>
<button type="submit" name="ss">SUBMIT</button>
</form>
<div class="mutiple">
</div>
I want to select multiple items "not wants to take value" from option list and print into div having class named multiple.
For example, if I select Lotus and Sun Flower then I want to print Lotus and Sun Flower not only its value.

If you want to make it with JavaScript, you can refer to the following code:
<form method="post">
<select name="item[]" multiple>
<option value="1">Lotus</option>
<option value="2">Sun Flower</option>
<option value="3">MNC</option>
<option value="4">DELL</option>
<option value="5">LENOVO</option>
</select>
<button type="submit" name="ss">SUBMIT</button>
</form>
<div class="multiple"></div>
<script>
$('select[name=item]').on('change', function() {
var ul = $('<ul>');
$('.multiple').empty();
$(this).find('option').each(function(index, element) {
if($(element).is(':selected')) {
ul.append('<li>' + $(element).text() + '</li>');
}
});
$('.multiple').html(ul);
});
</script>
or if you want to make it with PHP, here the code is:
if(!empty($_POST)) {
$products = array(
'1' => 'Lotus',
'2' => 'Sun Flower',
'3' => 'MNC',
'4' => 'DELL',
'5' => 'LENOVO'
);
echo "<ul>";
foreach($_POST['item'] as $item) {
echo "<li>{$products[$item]}</li>";
}
echo "</ul>";
}

You need to add brackets to the name:
<select name="item[]" multiple>
then on the server side item will be an array:
var_dump($_POST['item']);
You can put the text as the value of your select:
<select name="item[]" multiple>
<option value="Lotus">Lotus</option>
<option value="Sun Flower">Sun Flower</option>
<option value="MNC">MNC</option>
<option value="DELL">DELL</option>
<option value="LENOVO">LENOVO</option>
</select>
If you don't want to change the values, then you should map them using a DB or perhaps an array:
$pcs = [
"1"=>"Lotus",
"2"=>"Sun Flower",
"3"=>"MNC",
"4"=>"DELL",
"5"=>"LENOVO"
];
foreach($_POST['item'] as $key){
echo $pcs[$key];
}

It's easy :D
<script>
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
var return_div = result;
document.getElementById("selections").innerHTML = return_div;
}
</script>
<select multiple>
<option value="1">Lotus
<option value="2">Sun Flower
<option value="3">MNC
<option value="4">DELL
<option value="5">LENOVO
</select>
<button onclick="var el = document.getElementsByTagName('select')[0]; getSelectValues(el);">Show selected values</button>
<div>
<h1 id="selections"></h1>
</div>
Look this example:
https://jsfiddle.net/pm67kwkw/3/

Related

how to use a javascript variable inside html tag

I have a form in this There are two field One is Search and other is Option When i select any value from Search field the value of Option field will change.Value of Second field are different datalist defines as datalist1,datalist2,datalist3.....I want the value given in List attribute of Second filed to be same as the variable value in java script.i Tried the following code this code is not giving any output.
function random() {
var a = document.getElementById('search').value;
if (a === "sampleid") {
var datalist = datalist1;
} else if (a === "facility") {
var datalist = datalist1;
} else if (a === "user") {
var datalist = datalist3;
} else if (a === "affiliation") {
var datalist = datalist4;
} else if (a === "status") {
var datalist = datalist5;
} else if (a === "btr") {
var datalist = datalist6;
} else if (a === "type") {
var datalist = datalist7;
}
document.getElementById('option').innerHTML = datalist;
}
<form class="form-inline" method="post" action="search-sample.php">
<div class="col-md-5" align="center">
<label class="search">SEARCH BY-</label>
<select type="text" name="SEARCH" id="search" class="form-control" onchange="random()">
<option value="SELECT TYPE">SELECT TYPE</option>
<option value="sampleid">SAMPLE-ID</option>
<option value="facility">FACILITY</option>
<option value="user">USER NAME</option>
<option value="affiliation">AFFILIATION</option>
<option value="status">STATUS</option>
<option value="btr">BTR</option>
<option value="type">SAMPLE TYPE</option>
<option value="date">DATE</option>
</select>
</div>
<div class="col-md-5" align="center">
<label class="search">OPTION</label>
<input type="text" class="form-control" id="option" name="facility" list=< ?php echo "datalist" ?> />
</div>
<datalist id="datalist1">
<option value=""> </option>
<?php
$sql = "SELECT * from tblfacility order by sampleid asc";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->sampleid);?>"><?php echo htmlentities($result->sampleid);?></option>
<?php }} ?>
</datalist>
Here is what you need to do.
Use quotes around the IDs of the datalists
Use setAttribute of the list attribute of the input
function random() {
var a = document.getElementById('search').value,
datalist = "datalist1";
if (a === "sampleid") {
datalist = "datalist1";
} else if (a === "facility") {
datalist = "datalist1";
} else if (a === "user") {
datalist = "datalist2";
} else if (a === "affiliation") {
datalist = "datalist3";
} else if (a === "status") {
datalist = "datalist1";
} else if (a === "btr") {
datalist = "datalist2";
} else if (a === "type") {
datalist = "datalist3";
}
const inp = document.getElementById('option');
inp.value="";
inp.setAttribute("list", datalist)
}
<form class="form-inline" method="post" action="search-sample.php">
<div class="col-md-5" align="center">
<label class="search">SEARCH BY-</label>
<select type="text" name="SEARCH" id="search" class="form-control" onchange="random()">
<option value="SELECT TYPE">SELECT TYPE</option>
<option value="sampleid">SAMPLE-ID</option>
<option value="facility">FACILITY</option>
<option value="user">USER NAME</option>
<option value="affiliation">AFFILIATION</option>
<option value="status">STATUS</option>
<option value="btr">BTR</option>
<option value="type">SAMPLE TYPE</option>
<option value="date">DATE</option>
</select>
</div>
<div class="col-md-5" align="center">
<label class="search">OPTION</label>
<input type="text" class="form-control" id="option" name="facility" list="" />
</div>
<datalist id="datalist1">
<option value="A"> </option>
<option value="B"> </option>
<option value="C"> </option>
<option value="D"> </option>
</datalist>
<datalist id="datalist2">
<option value="AA"> </option>
<option value="BB"> </option>
<option value="CC"> </option>
<option value="DD"> </option>
</datalist>
<datalist id="datalist3">
<option value="AAA"> </option>
<option value="BBB"> </option>
<option value="CCC"> </option>
<option value="DDD"> </option>
</datalist>
</form>
I think what you're trying to do is assign a datalist to the "option" input based on the selected value in the select element, something like the following cut–down version of the OP:
// Select is a reference to the select element and
// is passed from the listener
function random(select) {
// Map select value to id of list to display
let map = {'sampleid': 'datalist1',
'facility': 'datalist2',
'user': 'datalist3'
};
// Get the option input
let option = document.getElementById('option');
// Clear the value
option.value = '';
// Assign the appropriate list
option.setAttribute('list', map[select.value]);
}
<form>
<label>SEARCH BY-</label>
<select name="SEARCH" id="search" onchange="random(this)">
<option value="SELECT TYPE">SELECT TYPE</option>
<option value="sampleid">SAMPLE-ID</option>
<option value="facility">FACILITY</option>
<option value="user">USER</option>
</select>
<!-- opton input to display options -->
<input list="" id="option" name="option">
<!-- datalists of options -->
<datalist id="datalist1">
<option value="datalist1 A">
<option value="datalist1 B">
<option value="datalist1 C">
</datalist>
<datalist id="datalist2">
<option value="datalist2 AA">
<option value="datalist2 BB">
<option value="datalist2 CC">
</datalist>
<datalist id="datalist3">
<option value="datalist3 AAA">
<option value="datalist3 BBB">
<option value="datalist3 CCC">
</datalist>
</form>
You should probably also disable the input if the selected value is the first one (i.e. select.selectedIndex = 0).
Use value instead of innerHTML.
document.getElementById('option').value= datalist;

how i can populate my search fields based on the parameters inside the URL

I am working on an asp.net web application and i have the following code to build a search fields section, which build the URL parameters based on the users' input:-
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(e) {
var count=1;
var s="";
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue!=null && inputvalue!="")
{
s = s+ "FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue+"&";
count++;
}
if(inputvalue2!=null && inputvalue2!="")
{
s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
count++;
}
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s);
});
});
</script>
Journal <input type="text" id="journal">
keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select>
title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select>
localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select>
locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select>
dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
Where when the user clicks on the search button, the user will be redirected to the /teamsites/Bib%20Test/Forms/search.aspxpage with the filter parameters inside the url, which will show the related records according to the parameters being passed.
now the filtering is working well.. but the problem i am facing is that after i redirect the user to this page /teamsites/Bib%20Test/Forms/search.aspx the filter fields values (such as the local currency, locations, title, etc..) will cleared out.
so can i using JavaScript to assign the filer fields their original values ? i mean can i extract the fields' values from the URL and assign it to them ? so after the user is being redirected to the /teamsites/Bib%20Test/Forms/search.aspx they can still see the filtering fields populated with the filtering values they have entered?
You can accomplish this by doing the following:
Parse the current page's query string to separate out its query parameters
Process those to match up filter field names with their values
Use $('#' + fieldName).val(value) to set the field values in the page
Below, as a demonstration, I'm passing in a hardcoded query string '?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b' into the populateSearchFields() function. In practice, you would use the three functions here, unmodified, but instead of that hardcoded value, pass in window.location.search.
// input: '?a=b&b=c&e=f'
// output: { a: 'b', b: 'c', e: 'f' }
function buildParameterMap(queryString) {
// ignore the ? at the beginning and split the query string into
// pieces separated by &
var pairs = queryString.replace(/^\?/, '').split('&');
var map = {};
pairs.forEach(function(pair) {
// further split each piece to the left and right of the =
// ignore pairs that are empty strings
if (pair) {
var sides = pair.split('=');
map[sides[0]] = decodeURIComponent(sides[1]);
}
});
return map;
}
// input: { FilterField0: 'Name', FilterValue0: 'Fred',
// FilterField1: 'age', FilterValue1: '30' }
// output: { name: 'Fred', age: '30' }
function buildFilterFieldMap(parameterMap) {
var maxFieldCount = 15;
var map = {};
for (var i = 0; i < maxFieldCount; i += 1) {
var filterFieldName = parameterMap['FilterField' + i];
if (filterFieldName) {
map[filterFieldName.toLowerCase()] = parameterMap['FilterValue' + i];
}
}
return map;
}
function populateSearchFields(queryString) {
// build a map from URL query string parameter -> value
var parameterMap = buildParameterMap(queryString);
// build a map from search field name -> value
var filterFieldMap = buildFilterFieldMap(parameterMap);
Object.keys(filterFieldMap).forEach(function(field) {
$('#' + field).val(filterFieldMap[field]);
});
}
populateSearchFields('?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Journal <input type="text" id="journal"> keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select> title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select> localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select> locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select> dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select> dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>
You want to send get request from one page to another. Do something like this:
Part I: send search request in the query string.
$(document).ready(function(){
$('#button').click(function(e) {
var count=1; //out of use
var s = []; //""; //empty array, not empty string
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue) // !=null && inputvalue!="") //it is redundant. null and empty string are **falsey**
{
s.push('journal='+inputvalue);
//or if you wish to keep your existing format (not recommended because it would produce problems on the search page)
//s.push("FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue);
//count++;
}
if(inputvalue2) //!=null && inputvalue2!="")
{
s.push('keywords='+inputvalue2);
//for existing format see previous comment
//s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
//count++;
}
/*
//same for other vars
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
*/
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s.join('&')); //Use the array here
});
});
Part II: Restore values in the search fields.
$(document).ready(function(){
var query = window.location.search.slice(1); //get ?.... less **?**
var terms = query.split('&'); //get pairs like key=value
for(var i = 0, term; term = terms[i]; ++i){ //loop the search terms
var detail = term.split('='); //journal=some
$('#'+detail[0]).val(detail[1]); //set the value provided fields have the same **id**s
}
});
Update based on comments
It is all about ASP.NET. .aspx page prepends server control IDs with parent IDs like parId$controlId. To avoid it and make the client script work set ClientIDMode="Static" attribute to the controls in search.aspx.
<asp:TextBox ID="keywords" runat="server" ClientIDMode="Static"></asp:TextBox>
Update 2
The OP is about ASP.NET. Generally speaking the result can be achieved without any client-side code.
Part I
<form method="GET" action="/search.aspx">
<input type="text" name="keywords" />
<select name="localcurrency">
<option value="USD">US Dollar</option>
<option value="EUR">Euro</option>
</select>
<!--other fields -->
<input type="submit" value="Search" />
</form>
Part II
<%-- search.aspx --%>
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["keywords"] != null)
this.keywords.Text = Request.QueryString["keywords"];
if (!string.IsNullOrEmpty(Request.QueryString["localcurrency"]))
localcurrency.SelectedValue = Request.QueryString["localcurrency"];
//other request query strings
// DoSearch();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="keywords" runat="server"></asp:TextBox>
<asp:DropDownList runat="server" ID="localcurrency">
<asp:ListItem Value="USD">US Dollar</asp:ListItem>
<asp:ListItem Value="EUR">Euro</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
Use this if you are not concerned about Internet Explorer or Edge.
When your page has loaded, you can read the search params with the help of URL API. Below is the code to get you started.
Note that this solution depends on being the form param's ID to be equal to the lower cased search param's name.
$(document).ready(() => {
// Change the value to window.location.href for working with browser's URL instead
const href = "http://yourhost.com?FilterField0=locations&FilterValue0=US&FilterField1=dropdown1&FilterValue1=b";
// Initializes the URL object with current location
const url = new URL(href);
// This array will contain all the FilterFields
const keys = [];
for (let entry of url.searchParams) {
if (entry[0].startsWith("FilterField")) {
keys.push(entry[0]);
}
}
keys.forEach(field => {
// Extract the index of FilterField
const idx = field[field.length - 1];
// Get the value of FilterField (this gives us the ID of the form field)
const formField = url.searchParams.get(field).toLowerCase();
// Set the value of form field using .val()
$("#" + formField).val(url.searchParams.get('FilterValue' + idx));
});
// Rest of the code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Journal <input type="text" id="journal"> keywords <input type="text" id="keywords">
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017">2017</option>
<option value="audi">Audi</option>
</select> title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select> localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select> locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select> dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select> dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<button type="button" id="button">search</button>

Using Javascript to check form elements and enabling/disabling the search button

I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.

JQuery convert string to link

I have 3 select fields, and the combined value of these I would like to use as a extra part of an url.
Here's the HTML code:
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
And the JavaScript:
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text(str);
})
.trigger('change');
https://jsfiddle.net/eZKUU/264/
Right now it's working.. after I select an option in all 3 of the selectfields I get an output like /squad/redblack/1985.
I would like to use this output in an url, so it would look like:
mysite.com/squad/redblack/1985
Is there an easy way of doing this? And also.. To only get the link visible after all three of the selectfields have an option selected?
You can use the following. Add an a element and keep it hidden until is completed. Update a element href attribute with selected options:
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
//update href with selected values
$("#mySite").attr("href", "mysite.com/" + str);
});
//keep anchor element hidden until all three options is selected
$("#mySite").toggle($("#cos").find("option:selected").length > 0 && $("#color").find("option:selected").length > 0 && $("#year").find("option:selected").length > 0);
$("div#output").text(str);
})
.trigger('change');
#mySite {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/>
<br/>
<div id="output"></div>
<a id="mySite" href="#">Redirect Link</a>
You can check to see if the number of selected options is the same amount as the number of select elements.
var selectedAllLength = $("select").length;
$("select").change(function () {
var str = location.origin;
var selected = $("select option:selected");
var selectedCount = selected.length;
if(selectedCount == selectedAllLength) {
selected.each(
function () {
str += $(this).attr('value');
}
);
$("#output").html('<a href=' + str + '>The link is here</a>');
}
})
.trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
To only get the link after all three have been selected, simply use an if statement to only generate and display the link if 3 options are selected. To make it a URL, just append the path you get to the base URL. Something like:
$("select").change(function () {
var str = "";
if(#("select option:selected").length === 3){
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text("mysite.com" + str);
// Or, if you want a clickable link and not just a URL:
// $("div#output").append($("<a>").attr({href: "mysite.com" + str}).append("Click me"));
}
})
.trigger('change');

Changing one form value based on onChange of another with javascript

I can't seem to get this function to work out. I'm trying to change the "business" input value of my form based on an amount selected in the "amount" dropdown. What am I missing!!! I've been trying this for an hour.
<script type="text/javascript">
function chPy()
{
var businessvar = "paypals#ramatico.com";
if (document.forms['5'].amount.value > 11){
businessvar = "paypall#ramatico.com"
}
document.forms['5'].business.value = businessvar;
}
</script>
<form name="5">
<select name="amount" OnChange="chPy()">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
Ok. The next step. I have about 100 of these forms on a page. Instead of creating one for each form, I'd like to have one script that changes based on which form is being changed with "onChange". Each of the forms on the page have values of the same name (but not ID) (they are for paypal). I think it will be ok if I can change the"formname" in the following: "document.forms['formname']" based on a variable populated by something like chPy("formname") etc..... I can't seem to get that to work either.
Removing the form reference would take care of both of your items.
<script type="text/javascript">
function chPy(oSelect)
{
var businessvar = "paypals#ramatico.com";
if (oSelect.form.amount.value > 11){
businessvar = "paypall#ramatico.com"
}
oSelect.form.business.value = businessvar;
}
</script>
<form name="5">
<select name="amount" OnChange="chPy(this)">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
Problem is that you are using a number as form name.
Add some letters to the name and it will work:
<script type="text/javascript">
function chPy()
{
var businessvar = "paypals#XYZ.com";
if (document.forms['form5'].amount.value > 11){
businessvar = "paypall#XYZ.com"
}
document.forms['form5'].business.value = businessvar;
}
</script>
<form name="form5">
<select name="amount" OnChange="chPy()">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input name="business" type="text" value="">
</form>
HTML:
<form name="form5">
<select name="amount">
<option value="na">Select</option>
<option value="1.00">$1</option>
<option value="5.00">$5</option>
<option value="10.00">$10</option>
<option value="15.00">$15</option>
<option value="20.00">$20</option>
<option value="25.00">$25</option>
</select>
<input type="text" name="business">
</form>
JavaScript:
var form5 = document.forms['form5'];
form5.amount.onchange = function() {
form5.business.value =
(this.value > 11 ? 'paypall' : 'paypals') + '#ramatico.com';
}
Live demo: http://jsfiddle.net/Fx7zh/
For multiple forms, you can use this JavaScript code:
for (var i = 0, l = document.forms.length; i < l; i++) {
document.forms[i].amount.onchange = function(i) {
this.form.business.value =
(this.value > 11 ? 'paypall' : 'paypals') + '#ramatico.com';
}
}
Live demo: http://jsfiddle.net/Fx7zh/2/

Categories

Resources