I have a custom eCommerce build for a client, which contains inputs that need to be sent to the server for hashing before the form can post.
The basic setup contains two select fields, one for the flavor name and another for its corresponding quantity. The user can Add Additional Flavor, which adds another set of flavor name and quantity selects.
Since the number of flavors (and their quantities) are dynamic, I need hash these values right before the form is posted via AJAX.
How do I create the constructor function for the JSON example below so that I can post the users values to my PHP script via JSON.stringify()
Basic JSON format I (think) I am after:
var flavorSelection {
flavor1 : ["Bacon", "1"],
flavor2 : ["Cheezy", "2"],
flavor3 : ["Cheezy", "1"]
}
Sample select fields
<div>
<select name="flavors">
<option name="bacon" value="bacon">Bacon</option>
<option name="cheezy" value="cheezy">Cheezy</option>
</select>
<select name="qty">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
</select>
</div>
You need to adjust your html markup to send arrays to your server
<div>
<select name="flavors[]">
<option name="bacon" value="bacon">Bacon</option>
<option name="cheezy" value="cheezy">Cheezy</option>
</select>
<select name="quantities[]">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
</select>
</div>
not sure if it's the best way, but you will need to rely on the array indices to pair up your data.
you can easily loop and build your json the following way:
$flavors = $_POST['flavors'];
$quantities = $_POST['quantities'];
$json = array();
for($i = 1; $i <= count($flavors) $i++){
$json[] = array('flavor'.$i => array(
flavors[$i], quantities[$i]
));
}
echo json_encode($json);
That will give you the desired json, i don't know about hashing though.
You can just do:
<div>
<select name="flavors[]">
<option name="bacon" value="bacon">Bacon</option>
<option name="cheezy" value="cheezy">Cheezy</option>
</select>
<select name="qty[]">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
</select>
</div>
In PHP, when you use [] after form input names, the $_POST["field_name"] will receive an array.
then if you have 3 diferent flavors, your $_POST["flavors"] will receive an array with values "flavor one", "flavor two", "flavor three".
And your $_POST["qty"] will receive an array with the respective quantities of flavors, in the same order.
Then you use jQuery.serialize() to format your form data to submit using jQuery.ajax().
Related
I got a select tag with some options in a HTML form:
(the data will be collected and processed using PHP)
Testing:
<select name="Testing">
<option value="1"> One
<option value="2"> Two
<option value="3"> Three
</select>
Is it possible for an option to carry multiple values like when a user selects
"One", then a few other values related to this option will be written to the Database.
How should I design the select Tag so that each of the options can carry one than one value like this:
<select name="Testing">
<option value="1" value="2010"> One
<option value="2" value="2122"> Two
<option value="3" value="0"> Three
</select>
One way to do this, first one an array, 2nd an object:
<select name="">
<option value='{"num_sequence":[0,1,2,3]}'>Option one</option>
<option value='{"foo":"bar","one":"two"}'>Option two</option>
</select>
I achieved it by using the PHP explode function, like this:
HTML Form (in a file I named 'doublevalue.php':
<form name="car_form" method="post" action="doublevalue_action.php">
<select name="car" id="car">
<option value="">Select Car</option>
<option value="BMW|Red">Red BMW</option>
<option value="Mercedes|Black">Black Mercedes</option>
</select>
<input type="submit" name="submit" id="submit" value="submit">
</form>
PHP action (in a file I named doublevalue_action.php)
<?php
$result = $_POST['car'];
$result_explode = explode('|', $result);
echo "Model: ". $result_explode[0]."<br />";
echo "Colour: ". $result_explode[1]."<br />";
?>
As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model, and colour).
On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated, and labelled them so you can see the effect this is causing.
its possible to have multiple values in a select option as shown below.
<select id="ddlEmployee" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-city="Washington" data-doj="20-06-2011">John</option>
<option value="2" data-city="California" data-doj="10-05-2015">Clif</option>
<option value="3" data-city="Delhi" data-doj="01-01-2008">Alexander</option>
</select>
you can get selected value on change event using jquery as shown below.
$("#ddlEmployee").change(function () {
alert($(this).find(':selected').data('city'));
});
You can find more details in this LINK
one option is to put multi value with comma seperated
like
value ="123,1234"
and in the server side separate them
When I need to do this, I make the other values data-values and then use js to assign them to a hidden input
<select id=select>
<option value=1 data-othervalue=2 data-someothervalue=3>
//...
</select>
<input type=hidden name=otherValue id=otherValue />
<input type=hidden name=someOtherValue id=someOtherValue />
<script>
$('#select').change(function () {
var otherValue=$(this).find('option:selected').attr('data-othervalue');
var someOtherValue=$(this).find('option:selected').attr('data-someothervalue');
$('#otherValue').val(otherValue);
$('#someOtherValue').val(someOtherValue);
});
</script>
What about html data attributes?
That's the easiest way.
Reference from w3school
In your case
$('select').on('change', function() {
alert('value a is:' + $("select option:selected").data('valuea') +
'\nvalue b is:' + $("select option:selected").data('valueb')
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<select name="Testing">
<option value="1" data-valuea="2010" data-valueb="2011"> One
<option value="2" data-valuea="2122" data-valueb="2123"> Two
<option value="3" data-valuea="0" data-valueb="1"> Three
</select>
In HTML:
<SELECT NAME="Testing" id="Testing">
<OPTION VALUE="1,2010"> One
<OPTION VALUE="2,2122"> Two
<OPTION VALUE="3,0"> Three
</SELECT>
For JS:
var valueOne= $('#Testing').val().split(',')[0];
var valueTwo =$('#Testing').val().split(',')[1];
console.log(valueOne); //output 1
console.log(valueTwo); //output 2010
For PHP:
$selectedValue= explode(',', $value);
$valueOne= $exploded_value[0]; //output 1
$valueTwo= $exploded_value[1]; //output 2010
I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.
HTML
<select class="example">
<option value="1" data-value="A">One</option>
<option value="2" data-value="B">Two</option>
<option value="3" data-value="C">Three</option>
<option value="4" data-value="D">Four</option>
</select>
JS
$('select.example').change(function() {
var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');
console.log(other_val);
});
If you're goal is to write this information to the database, then why do you need to have a primary value and 'related' values in the value attribute? Why not just send the primary value to the database and let the relational nature of the database take care of the rest.
If you need to have multiple values in your OPTIONs, try a delimiter that isn't very common:
<OPTION VALUE="1|2010">One</OPTION>
or add an object literal (JSON format):
<OPTION VALUE="{'primary':'1','secondary':'2010'}">One</OPTION>
It really depends on what you're trying to do.
Put values for each option like
<SELECT NAME="val">
<OPTION value="1:2:3:4"> 1-4
<OPTION value="5:6:7:8"> 5-8
<OPTION value="9:10:11:12"> 9-12
</SELECT>
At server side in case of PHP, use functions like explode
[array] = explode([delimeter],[posted value]);
$values = explode(':',$_POST['val']
The above code returns an array that has only the numbers and the ':' get removed
Simplest way to do this:
<select name="demo_select">
<option value='{"key1":"111","key2":"222"}'>option1</option>
<option value='{"key1":"333","key2":"444"}'>option2</option>
</select>
on controller decode the request value as given below:
$values = json_decode($request->post('demo_select'));
$val1 = $values->key1;
$val2 = $values->key2;
echo "Value 1: ".$val1;
echo "Value 2: ".$val2;
output for the first option:
Value 1: 111
Value 2: 222
output for the second option:
Value 1: 333
Value 2: 444
Use a delimiter to separate the values.
<select name="myValues">
<option value="one|two">
</select>
<?php>
$value = filter_input(INPUT_POST, 'myValues');
$exploded_value = explode('|', $value);
$value_one = $exploded_value[0];
$value_two = $exploded_value[1];
?>
Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.
Instead of storing the options on the client-side, another way to do this is to store the options as sub-array elements of an associative/indexed array on the server-side. The values of the select tag would then just contain the keys used to dereference the sub-array.
Here is some example code. This is written in PHP since the OP mentioned PHP, but it can be adapted to whatever server-side language you are using:
<FORM action="" method="POST">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
PHP:
<?php
$options = array(
1 => array('value1' => '1', 'value2' => '2010'),
2 => array('value1' => '2', 'value2' => '2122'),
3 => array('value1' => '3', 'value2' => '0'),
);
echo 'Selected option value 1: ' . $options[$_POST['Testing']]['value1'] . '<br>';
echo 'Selected option value 2: ' . $options[$_POST['Testing']]['value2'] . '<br>';
This may or may not be useful to others, but for my particular use case I just wanted additional parameters to be passed back from the form when the option was selected - these parameters had the same values for all options, so... my solution was to include hidden inputs in the form with the select, like:
<FORM action="" method="POST">
<INPUT TYPE="hidden" NAME="OTHERP1" VALUE="P1VALUE">
<INPUT TYPE="hidden" NAME="OTHERP2" VALUE="P2VALUE">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
Maybe obvious... more obvious after you see it.
<select name="student" id="student">
<option value="">Select Student</option>
<option value="Student Name|Roll No">Student Name</option>
</select>
<input type="submit" name="submit" id="submit" value="submit"></form>
i use data-attribute to get the value with simple javascript and blade template.
<select class="form-control" id="channelTitle" name="channelTitle" onchange="idChannels()">
#foreach($post['channels'] as $channels)
<option value="{{ $channels->channel_title }}" data-id="{{ $channels->channel_id }}">{{ $channels->channel_title }}</option>
#endforeach
</select>
the data-id result here
<div class="form-group">
<strong>Channel Id:</strong>
<input type="text" name="channelId" id="channelId" class="form-control" placeholder="Channel Id">
</div>
javascript
<script>
function idChannels(){
var elem=document.getElementById("channelTitle");
var id = elem.options[elem.selectedIndex].getAttribute('data-id');
document.getElementById("channelId").value = id;
} </script>
you can use multiple attribute
<SELECT NAME="Testing" multiple>
<OPTION VALUE="1"> One
<OPTION VALUE="2"> Two
<OPTION VALUE="3"> Three
I am trying to generate a list of options in a select dynamically based on the selection in another select by referencing a value in an array of objects.
<select id="radar">
<option value="15">City1</option>
<option value="64">City2</option>
</select>
<select id="beam">
</select>
Objects:
var radars = {
"city1": {
"name": "city1",
"maxBeams": 16
},
"city2": {
"name": "city2",
"maxBeams": 3
}
}
When a radar option is selected for example City2, I would like to fill the beam select with an option for as many maxBeams that have thee option value and text to simply be that index number:
<select id="beam">
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3</option>
</select>
What is the simplest way to accomplish this and make it easy to update?
You really shouldn't be using javascript to dynamically generate content like this. You should be using a framework like Vue.js, React, or Angular. You can homebrew a solution directly with javascript but you're just adding to your technical debt.
You should be doing something like this:
<div vue="app">
<select v-model="city_group">
<option disabled value="">Please select one</option>
<option v-for="c in cities">{{c}}</option>
</select>
<select v-if="city_group != ''" v-model="city">
<option disabled value="">Please select one</option>
<option v-for="c in city_info[city_group]">{{c}}</option>
</select>
<h1>My city group is {{city_group}}</h1>
<h1>My city is {{city}}</h1>
</div>
Notice how the content is based on data.
https://codepen.io/Snorghma/pen/QWWjOmq
https://v2.vuejs.org/v2/guide/forms.html#Select
https://v2.vuejs.org/v2/guide/list.html
I am building a fairly complex form-- I need to copy some data between one and another and I am using jQuery to do this. The only road block I am running into is setting the state.
I have two drop downs, one us using the full state name as the value and the other is using the state abbreviation as the value. The names are the same-
so on form 1 it looks like
<option value="Illinois">Illinois</option>
and form 2 it looks like
<option value="IL">Illinois</option>
Each form has its own unique css selector. How can I set the selected value of form 2 to match what is in form 1 using jQuery?
I do not have any control over the forms, just need to manipulate the input. Have tried using a name selector in jQuery, but I'm not having any luck.
Thank you.
You can do something like this
<select id="fullName">
<option value="Maryland" data-abbr="MD">Maryland</option>
<option value="Illinois" data-abbr="IL">Illinois</option>
<option value="Delaware" data-abbr="DE">Delaware</option>
</select>
<select id="abbr">
<option value="MD">Maryland</option>
<option value="IL">Illinois</option>
<option value="DE">Delaware</option>
</select>
And your jQuery
$('body').on('change', '#fullName', function(){
var abbr = $(this).find('option:selected').data('abbr');
$('#abbr').val(abbr);
});
Try this
<form id="form1" name="form1">
<select name="states" onchange="changeselect(this)">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</form>
<form id="form2" name="form2">
<select name="states">
<option value="opt1">option1</option>
<option value="opt2">option2</option>
<option value="opt3">option3</option>
<option value="opt4">option4</option>
<option value="opt5">option5</option>
</select>
</form>
function changeselect(elem)
{
var value1 = $(elem).val();
$('#form2 select option').removeAttr('selected');
$('#form2').find('select option').each(function(){
var value2 = $(this).html();
if(value1 == value2)
{
var selected = $(this).attr('value');
$('#form2 select').val(selected);
}
});
}
If you create 2 arrays which exactly correspond with one another:
var StateNames = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
var StateAbbreviations = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
You can:
get the value from the first option list;
find that value's index in the first array; (hint: use indexOf)
use the same index to find out what the corresponding abbreviation is in the second array;
use the returned abbreviation to locate the correct option in the second option list
I am trying to create a rating system.
I have an XML file, which has the follow information:
<?xml version="1.0" encoding="ISO-8859-1"?>
<PROGRAMMEDATA>
<PROGRAMME id="1">
<TITLE>Arrow</TITLE>
<IMAGE>img/arrow.jpg</IMAGE>
<POINTS>0</POINTS>
</PROGRAMME>
...etc
<PROGRAMMEDATA>
I then have a form, with programme options and 1 to 5 score.
<form>
<select id="name">
<option selected value=""></option>
<option value="1">Arrow</option>
<option value="2">You, Me and Dupree</option>
<option value="3">Fargo</option>
<option value="4">Flash</option>
</select>
<select id="rating">
<option selected value="">stars</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" value="Submit rating" onClick="saveRating()" />
</form>
The idea is you can choose a programme and then choose a rating. You can then submit that and the rating will then be added to the corresponding programme in the XML file.
I have tried to capture the form values with javascript, but I then don't know how to store the value in the XML file.
var name = document.getElementById("name").value;
var rating = document.getElementById("rating").value;
Another way I've thought about is using PHP, and using DOMDocument, however I can't get it to append the POINTS, it only adds to the bottom of the XML file.
Any help greatly appreciated.
Something like this should work.
$file ="ratings_file.xml";
$title="test";
$image="img/arrow.jpg";
$points=0;
//load xml object
$xml= simplexml_load_file($ratings_file);
//assign title
$xml->PROGRAMME->title = $title;
//assign image
$xml->PROGRAMME->image = $image;
//assign points
$xml->PROGRAMME->points = $points;
//store the value into the file
file_put_contents($ratings_file, $xml->asXML());
I want to send both the value and key of the option box when I submit a form. I feel like this should be pretty simple, but I'm unsure how to do it. Below is a snippet from my form to demonstrate what I'm referencing:
<form name='form' onSubmit="return checkForm();" action="../servlet/AccountRequest">
<select name="type1">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
<br/><input type="button" id="Submit" onclick="checkForm(this.form)" value="Request" />
<input type="reset" value="Cancel"/>
</form>
In a normal scenario, if I selected "Option A" in the drop-down box, I would want to send the value, or "1". However, I want to actually send the value AND key of the selection, in this case both "1" and "Option A".
In my case, I call a checkForm() JavaScript function that validates form input (there are other fields, like First Name, Last Name, Email Address, and Password), which then forwards the parameters to a Java class (AccountRequest). I'm sure there is a way to store the key as a variable when the "Request" button is clicked, I just don't know how.
Any help would be much appreciated!
You could play with a jSON representation of your data:
<select name="type1">
<option value="{'1':'Option A'}">Option A</option>
<option value="{'2':'Option B'}">Option B</option>
</select>
It might not be the approach you were expecting, but you could send the key/value pair as your value and parse it when you receive it server-side.
<select name="type1">
<option value="1,Option A">Option A</option>
<option value="2,Option B">Option B</option>
</select>
In HTML, this is impossible: the data contributed by a select element is defined to be the value attribute of the selected option, when present (otherwise the content of the selected option element).
In JavaScript, it would be pretty easy, once you have decided how the content (“key” in your description) should be passed. At the simplest, you could append the content to the value attribute, with some separator between the strings; then you would have to parse that server-side, but that would be simple too.
However, it is part of the very idea of option elements that the content is the visible string in the user interface, understandable to the user, and the value attribute is the machine-readable easily processable data. In good design, they are kept as separate, not combined; the server should only need the data from the value attribute; otherwise there is a design flaw that should be fixed.
You could add this code to get the text of your selected <option> tag in your checkform function:
var select = document.getElementsByName("type1")[0]; // get select element - simpler if it has an ID because you can use the getElementById method
var options = select.getElementsByTagName("option"); // get all option tags within the select
for (i = 0; i < options.length; i++) { // iterate through all option tags
if (options[i].value == select.value){ // if this option is selected
var key = options[i].innerHTML; // store key of selected option here
}
}
DEMO, which tells you the key that's selected
Use a compound value, then parse it out on the server:
<option value="1_A">Option A</option>
you can send the value with an input type hidden
1.-choose the default value:
<input type="hidden" id="theValue" name="type1Value" value="Option A"/>
2.-add onChange function to your select, which changes previous hidden value
<select id="type1" name="type1" onChange="updateValue()">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
assuming you are using jQuery:
function updateValue(){
var value= $('#type1').find(":selected").text();
$('#theValue').val(value);
}
so the value of the select will be sent in type1Value variable, EASY!!
using React js
I want to get two values from the option at the same time
so, I use the Split method
var string = "0,1";
var array = string.split(",");
alert(array[0]);
I create a sting on option
const getKioskSelectedUsageType=(e)=>{
let sl = e.target.value
let array = sl.split(",")
console.log("check :- ",array[1] )
}
<select
id=""
className="form-control"
value={kioskSelect}
aria-label="kioskSelect"
name="kioskSelect"
title="kioskSelect"
onChange={(e) => getKioskSelectedUsageType(e)}
style={{ color: "#495057" }}
>
<option value="">Select Kiosk</option>
{kioskConfiData.map((item, i) => {
return (
<React.Fragment key={i}>
<option value={`${item.kioskid},${item.language}`}>
{item.location}
</option>
</React.Fragment>
);
})}
</select>