Submit form with 2 select fields to go to different pages - html

I run a joomla site and would like to create an html form within an article that does the following:
<form action="compare.html" method="post">
<select id="select1" name="select1" required="">
<option value="A">OptionA</option>
<option value="B">OptionB</option>
<option value="C">OptionC</option>
</select>
<select id="select2" name="select2" required="">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
<input id="submit" type="submit" />
</form>
After selecting from the 2 dropdowns and submitting the form, the user should go to a page based on the selected options. E.g.
OptionA + Option1 --> goes to page_97.html
OptionA + Option2 --> goes to page_451.html
OptionA + Option3 --> goes to page_13.html
OptionB + Option1 --> goes to page_77.html
and so on.
I was hoping this could be done in pure html or with some simple JS (I'm a newbie to js,php)?

I came up with the following solution which works, but I am sure this could be optimized.
<select id="select1" name="select1" required="" oninput="join_names();">
<option value="">=== SELECT ===</option>
<option value="A">OptionA</option>
<option value="B">OptionB</option>
<option value="C">OptionC</option>
</select>
<br>
<select id="select2" name="select2" required="" oninput="join_names();">
<option value="">=== SELECT ===</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
<br>
<button id="compareButton" class="float-left submit-button">COMPARE</button>
<script type="text/javascript">
var urlMap = {
"default" : "/default.html",
"A1" : "/page_97.html",
"A2" : "/page_451.html",
"A3" : "/page_13.html"
"A3" : "/page_77.html"
}
function join_names() {
var input_select1 = document.getElementsByName('select1')[0].value;
var input_select2 = document.getElementsByName('select2')[0].value;
var var_select12 = concatenate(input_select1, input_select2);
var var_select12_url = getMapValue(urlMap,var_select12);
document.getElementById("compareButton").onclick = function () {
window.location.href = var_select12_url;
};
}
function concatenate(string_one, string_two) {
return string_one+string_two;
}
function getMapValue(obj, key) {
if (obj.hasOwnProperty(key)) {
return obj[key];
} else {
return obj['default'];
}
}
</script>

Related

JQuery match different id with the last same number

I have example HTML code like this:
<select id="label_1">
<option></option>
</select>
<select id="item_1">
<option></option>
</select>
<select id="label_2">
<option></option>
</select>
<select id="item_2">
<option></option>
</select>
How do I write jQuery code to match the label and item id with the same number?
if($("#label_" + [/[0-9]+$/]) == $("#item_" + [/[0-9]+$/])) {
//do something
}
You can find all the label elements first and then iterate them to find the matching item elements
$("select[id^='label_']").each((_, label) => {
const idSuffix = label.id.split("_").pop();
const item = $(`#item_${idSuffix}`);
// now you have both `label` and `item`
});
The vanilla JS version isn't much different
document.querySelectorAll("select[id^='label_']").forEach((label) => {
const idSuffix = label.id.split("_").pop();
const item = document.getElementById(`item_${idSuffix}`);
// now you have both `label` and `item`
});
If you want to do one time : return false
$.each($("select[id^= 'label_']"), function(){
let num = this.id.replace('label_', '')
let equal = $(this).value === $("#item_" + num).value
if(equal) {
// do something
// if you want to run one times ( return false)
return false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="label_1">
<option value="1" selected>1</option>
</select>
<select id="item_1">
<option value="1" selected>1</option>
</select>
<select id="label_2">
<option value="2" selected>2</option>
</select>
<select id="item_2">
<option value="2" selected>2</option>
</select>

Restrict the input field value of a form to options only

I am using a form to insert the value to the database.I want the stationerytype field to insert only the option value.My code allows user to insert the typed value.i dont want to insert this typed value.
There are two datalist for the option and the value of datalist depends upon the value selected on 'purpose' field. My code is
<select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required />
<option></option>
<option value="Meeting">Meeting</option>
<option value="Departmental">Departmental</option>
</select>
</div>
<script>
function random() {
document.querySelector('[name="stationerytype[]"]').value = ""
var a = document.getElementById('purpose').value;
if (a === "Meeting") {
var datalist = "datalist1";
} else if (a === "Departmental") {
var datalist = "datalist2";
}
document.querySelector('[name="stationerytype[]"]').setAttribute("list", datalist)
}
</script>
<td><input type="text" name="stationerytype[]" id="stationerytype" class="form-control" autocomplete="off" required>
<datalist id="datalist1">
<option value=""></option>
<option value="MEETING PEN">MEETING PEN</option>
<option value="NOTEPAD">NOTEPAD</option>
<option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
</datalist>
<datalist id="datalist2">
<option value=""></option>
<option value="A4 GREEN REAM">A4 GREEN REAM</option>
<option value="A4 WHITE REAM">A4 WHITE REAM</option>
<option value="CELLOTAPE(BROWN)">CELLOTAPE(BROWN)</option>
</datalist>
</td>
Refering to this post, you have to set the pattern attribute of your input. If the pattern has been set, if the user select any other option other than the value from data list, the input will be invalid.
If the input is not a valid one, you can clear the value of the input on change event.
Working fiddle
function random() {
const input = document.querySelector('[name="stationerytype[]"]');
input.value = ""
var a = document.getElementById('purpose').value;
if (a === "Meeting") {
var datalist = "datalist1";
} else if (a === "Departmental") {
var datalist = "datalist2";
}
const options = Array.from(document.getElementById(datalist).options).map(option => option.value);
input.setAttribute("list", datalist);
input.setAttribute("pattern", options.join('|'));
}
function ondataListSelect() {
const input = document.getElementById('stationerytype');
if (!input.validity.valid) {
input.value = '';
}
}
<select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required >
<option></option>
<option value="Meeting">Meeting</option>
<option value="Departmental">Departmental</option>
</select>
<td>
<input type="text"
name="stationerytype[]"
id="stationerytype"
class="form-control"
onchange="ondataListSelect()"
autocomplete="off"
required>
<datalist id="datalist1">
<option value=""></option>
<option value="MEETING PEN">MEETING PEN</option>
<option value="NOTEPAD">NOTEPAD</option>
<option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
</datalist>
<datalist id="datalist2">
<option value=""></option>
<option value="A4 GREEN REAM">A4 GREEN REAM</option>
<option value="A4 WHITE REAM">A4 WHITE REAM</option>
<option value="CELLOTAPE(BROWN)">CELLOTAPE(BROWN)</option>
</datalist>
</td>

JQUERY - Custom HTML Option Data for IF Statement for Chained Selection

edit: see "Edit" Section for updated question
I am trying to make the second dropdown selection dependent of the first, using jquery.
get "data-type" of first selection
if "data-type" == "String" trigger filter change of second selections "data-foo" containing value N
HTML Selections
<select id="first" name="first-selection" class="form-control">
<option value="a" class="b" data-type="c">a</option>
</select>
<select id="second" name="second" class="form-control">
<option value="n" data-foo="m">n</option>
</select>
I used to following code to check if I am able to get the "data-type" value and display it. But any attempt to get the data for an if statement failed so far.
$('#first').change(function () {
var selected = $(this).find('option:selected');
$('#type').html(selected.data('type'));
}).change();
edit - code with if statement
how do I use "data-type" for an if statement?
EDIT
New code and jsfiddle to make myself clear
<select id="first" name="first-selection" class="form-control">
<option value="1" class="type1" data-type="snowboot">bli</option>
<option value="2" class="type2" data-type="nose">bla</option>
<option value="3" class="type3" data-type="head">blu</option>
</select>
<p>Test output: <span id="type"></span>.</p>
<select id="second" name="second-selection" class="form-control">
<option value="11" data-foo="green">one of three</option>
<option value="22" data-foo="red">two of three</option>
<option value="33" data-foo="red">three of three</option>
</select>
$(function(){
$('#first').change(function(){
var selected = $(this).find('option:selected');
$('#type').html(selected.data('type'));
}).change();
});
Question
How do I use "data-type" and put it as an if statement before the function? The following won't do anything
if ($('select[id=first] option').filter(':selected').type() == "nose")
if(selected.data('type') == "nose")
var myvar = $('#first option:selected').data();
if(myvar == 'nose')
This is the code I want to run after the if statement:
var $firstvar= $("#first");
$secondvar= $("#second");
$options = $secondvar.find('option')
$firstvar.on('change', function () {
$secondvar.html($options.filter('[data-foo="' + 'red' + '"]'));
}).trigger('change');
This will do what you want. It will check, whether the selected option of the first select was of any of the types mentioned in the object conditions and will then go through all options of the second select and either show or hide them (using the jQuery .toggle(.toggle(!isNose||this.dataset.foo==="red")) method). The expression show=!found||this.dataset.foo===found will evaluate to true for all cases where found is undefined and to false only if found is "trueish" AND this.dataset.foo===found is false.
$(function() {
const conditions={nose:"red",head:"green"}; // add as many as you like ...
$('#first').change(function() {
let show,first=true; // first makes sure only ONE option can be set
const found=conditions[ $(this).find(":selected").data("type") ];
$('#second option').each(function(){
$(this).toggle(show=!found||this.dataset.foo===found);
if(first&&show) first=!(this.selected=true); // select first visible option
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="first" name="first-selection" class="form-control">
<option value="1" class="type1" data-type="snowboot">bli</option>
<option value="2" class="type2" data-type="nose">bla</option>
<option value="3" class="type3" data-type="head">blu</option>
</select>
<p>Test output: <span id="type"></span>.</p>
<select id="second" name="second-selection" class="form-control">
<option value="11" data-foo="green">one of three</option>
<option value="22" data-foo="red">two of three</option>
<option value="33" data-foo="red">three of three</option>
</select>

can we show content of datalist in input field rather than it's value

I want my calculation to run without showing it to the person using it so I want him to see only the content of input option, not value
example:
<option value="66.48">25 LIGHT</option>
when someone select this option his input field should show 25 LIGHT instead of 666.48.
NOTE: I cant use select, I have to use datalist because I want the user to get options by typing, as there are 100s of them. can I do this with data list?
please guide.
my code:
<form onsubmit="return false" oninput=" totalamount.value = Math.round(((Item.value * Quantity.value - (Item.value * Quantity.value *Percentage.value /100))+ Number.EPSILON) * 100) / 100 ;">
Percentage<input name="Percentage" id="Percentage" type="number">
<br />
<section class="container">
<div class="one">
Item<br/><input list="items" type="text" name="Item" id="Item" width="70%">
</div>
<div class="two">
Quantity <br/><input name="Quantity" id="Quantity" type="number">
</div>
</section>
<br/>
Total amount <output name="totalamount" id="totalamount" for="Item Quantity Percentage"></output>
</form>
<datalist id="items">
<option value="66.48">25 LIGHT</option>
<option value="88.64">25 MEDIUM</option>
<option value="103.41">25 HEAVY</option>
<option value="93.54">Regal 19/1.0</option>
<option value="69.8">Regal 19/1.2</option>
<option value="69.8">Regal 19/1.4</option> </datalist>
Use the selectedIndex property of the select field to get the selected <option> element as a node. Then get the innerHTML of that node:
var select = document.querySelector("select");
select.onchange = function() {
var html = this.options[this.selectedIndex].innerHTML
console.log(html);
}
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
In case you are using a <datalist>, you need to manually lookup the option whose value matches the value of your <datalist>:
var input = document.querySelector("input");
var list = document.getElementById("nums");
input.onchange = function() {
var selected = Array.from(list.options).filter(opt => {
return opt.value == input.value;
})[0];
console.log(selected.innerHTML);
}
<input list="nums"/>
<datalist id="nums">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</datalist>

Generating links in HTML

I have a form with two datalist and I would like to generate a link based on the user's selection.
<form>
<input list="Cars">
<datalist id="Cars">
<option value="Honda" selected>Honda</option>
<option value="Mazda">Mazda</option>
<option value="Ford">Ford</option>
<option value="Nissan">Nissan</option>
<option value="Subaru">Subaru</option>
</datalist>
<input list="Years">
<datalist id="Years">
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</datalist>
<input type="reset">
</form>
For an example, if user chooses Honda and 2017, then the link appears and the address is Honda/2017.net. If the user chooses Subaru and 2015 then the address is Subaru/2015.net and etc.
I can input the different href manually in the code but I am not sure how you make one link change based on selection?
You need Javascript for the so called dynamic html or DHTML. Could be done like this:
<!DOCTYPE html>
<script type="text/javascript">
function generateLink()
{
var brand = document.getElementById('carBrand').value;
var year = document.getElementById('carYear').value;
document.leform.action =brand + '/' + year + '.html';
return true;
}
</script>
<form name="leform" onsubmit="return generateLink();">
<input list="Cars" id='carBrand'>
<datalist id="Cars">
<option value="Honda" selected>Honda</option>
<option value="Mazda">Mazda</option>
<option value="Ford">Ford</option>
<option value="Nissan">Nissan</option>
<option value="Subaru">Subaru</option>
</datalist>
<input list="Years" id='carYear'>
<datalist id="Years">
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</datalist>
<input type="reset">
<input type="submit">
</form>
What happens?
If the submit Button is clicked, the generateLink() function is called. onsubmit="return generateLink();"
In the generateLink() function the value of the selected option for the car/brand and the year are read from html using the getElementById function.
Then the extracted values for the brand and the year are used to generate the corresponding link via concatenation of car, a slash, the year and finally the string '.html'.
The link the form will redirect to is set in the forms action attribute. document.leform.action
To process data submitted by the form you will need some kind of CGI mechanism: https://en.wikipedia.org/wiki/Common_Gateway_Interface
You could use PHP to pass data further to a database for example.
Hope this helps ^^-d
PS: You could also want to implement the page that follows the form (action=) in PHP as dynamic content. Using a HTTP GET Request this could look like /show.php?car=Subaru&Year=2016 which would save you from creating an html file per option (car X year = 15 files!). URLs of HTTP GET Requests can be bookmarked like Honda/2017.net. More info on this here: http://php.net/manual/en/reserved.variables.request.php
use below snippet as a boilerplate.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<input list="Cars" onchange="generateUrl()">
<datalist id="Cars">
<option value="Honda" selected>Honda</option>
<option value="Mazda">Mazda</option>
<option value="Ford">Ford</option>
<option value="Nissan">Nissan</option>
<option value="Subaru">Subaru</option>
</datalist>
<input list="Years" onchange="generateUrl()">
<datalist id="Years">
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</datalist>
<input type="reset">
</form>
<p id="generated">
</p>
<script type="text/javascript">
function generateUrl(){
var x = document.querySelector("[list='Cars']").value;
var y = document.querySelector("[list='Years']").value;
document.getElementById('generated').innerHTML = (x+y);
}
</script>
</body>
</html>
You can grab the values of the <datalist> using the onchange event; store them in a variable somewhere, then write it out to your link.
var car = '';
var year = '';
$("input[name=car-list]").on('change', function(){
car = $(this).val();
});
$("input[name=yr-list]").on('change', function(){
year = $(this).val();
});
$("input[name=submit]").on('click', function(){
$("#mylink").attr('href', car + '/' + year);
$("#mylink").html(car + '/' + year);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input list="Cars" name="car-list">
<datalist id="Cars">
<option value="Honda" selected>Honda</option>
<option value="Mazda">Mazda</option>
<option value="Ford">Ford</option>
<option value="Nissan">Nissan</option>
<option value="Subaru">Subaru</option>
</datalist>
<input list="Years" name="yr-list">
<datalist id="Years">
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</datalist>
<input type="button" name="submit" value="Submit">
<input type="reset">
</form>
<a id="mylink" href="">My Link</a>