How to store a javascript function value inside a php variable - javascript

function check_val(val) {
document.getElementById("select_action")=val;
alert(val);
return val;
}
this is my javascript function
<select name='select' id='select' onchange='check_val(this.value)'>
<option value='0'><------select------></option>
<option value='4'>apple</option>
<option value='5'>mango</option>
<option value='6'>berry</option>
</select>
<?php <input type=hidden name='select' value=???> //by using javascript I need the value
this is my select tag now I want to put the values inside a hidden field

a few things here:
to post into a different page from javascript, you could use .post(...) or $.ajax({ type: 'post',... there's an example of the latter in the answer here
hidden html inputs are useful for storing values, but they do not need to be inside php tags, which I think is what adeneo was pointing out
your hidden input does not have an id, only a name, and the name is the same as your select box
you are trying to reference something using getElementById("select_action"), but you don't have anything with that id.

Pam, you don't need php at all for this, just set the value of the hidden input in your javascript function with the manipulated val
function check_val(val) {
val++; // do things to val (add 1)
document.getElementById("hidden_input").value=val; //set value in the hidden input
return;
}
Make sure your hidden input has an ID
<select name="select" id="select" onchange="check_val(this.value)">
<option value='0'><------select------></option>
<option value='4'>apple</option>
<option value='5'>mango</option>
<option value='6'>berry</option>
</select>
<input id="hidden_input" type="hidden" name="hidden_input" value="0">
On the page that you are posting to, you will access the data in PHP with
echo $_POST['hidden_input'];
// or
echo $_REQUEST['hidden_input'];

Related

Change span text with selected option

I am on beginning of the coding life. I am trying to change text in span with selected option, but it gives me values not texts. For example, when I select the bus option, I want it to shows me the "bus" text. I do not want value number. Thanks in advance.
<select id="vehicles" onchange="showChange()">
<option value="1">Bus</option>
<option value="2">Car</option>
<option value="3">Plane</option>
</select>
<span id="vehicle"></span>
<script>
function showChange(){
var selected_vehicle = document.getElementById("vehicles").value;
document.getElementById("vehicle").innerText = selected_vehicle;
}
</script>
You can first pass this keyword to the function then get the text using selectedIndex of option.
<select id="vehicles" onchange="showChange(this)">
<option value="1">Bus</option>
<option value="2">Car</option>
<option value="3">Plane</option>
</select>
<span id="vehicle"></span>
<script>
function showChange(el){
var selected_vehicle = el.options[el.selectedIndex].text;
document.getElementById("vehicle").innerText = selected_vehicle;
}
</script>
If you keep the inline declarations from your HTML ( generally the preferred approach ) you can assign your event handlers in a separate file. Also, as a point of note - if you submit the form data in the traditional manner ( rather than with AJAX etc ) then the select element needs a name - an ID will NOT appear in the REQUEST array!
document.querySelector('select[name="vehicles"]').addEventListener('change',e=>{
e.target.nextElementSibling.textContent=[ e.target.value, e.target.options[e.target.options.selectedIndex].text].join(' ')
})
<select name='vehicles'>
<option selected hidden disabled>Select mode of transport
<option value='1'>Bus
<option value='2'>Car
<option value='3'>Plane
</select>
<span id='vehicle'></span>

How to use a submit button linked to a drop down list?

I got a dropdown select option and I wanted to be able to select one and click on the submit button and lead me to another page (NewYork.html,Toronto.html,NewJersey.html)
<form action="action_page.php">
<select>
<option value = "0">Select your Destination..</option>
<option value="1">New York</option>
<option value="2">Toronto</option>
<option value="3">New Jersey</option>
</select>
<input type="submit" value="Submit" class="myButton">
</form>
In your actionPage you have to redirect the user to the other page.
But you have also to check security and not redirect to something you don't know.
So you can use an associative array with your form values like $array = [1 => "newYork", 2 => "toronto"...] and then proceed to the redirection without forgetting to exit :
$redirect = $array[$_POST['value']] + ".html";
header("Location: /$redirect");
exit();
You can do this in your PHP code by using header() and use the value from the submitted form.
header('Location: /'.$submittedValue.'.html');
Obviously you'll need to check your form input first as you'll only get a numerical value from the drop down at the moment, but you can match that to a string to use in the header function.
Please note that the head function must be higher up the page than any echo, print_r() or any other functions that will output to the browser
You can set the value of option elements to URL of .html documents which user will be re-directed to; use event.preventDefault() to prevent form submission at submit event; if select .value is not "0", set location.href to select .value
html
<form>
<select>
<option value="0">Select your Destination..</option>
<option value="NewYork.html">New York</option>
<option value="Toronto.html">Toronto</option>
<option value="NewJersey.html">New Jersey</option>
</select>
<input type="submit" value="Submit" class="myButton">
</form>
javascript
document.querySelector("form")
.addEventListener("submit", function(e) {
e.preventDefault(); // prevent default action
var select = this.querySelector("select");
if (select.value !== "0") {
location.href = select.value;
}
})

Javascript producing a value into a form textbox on selection

Trying to figure out how I can produce text dynamically in a text box of a form using javascript.
I want to select a type of event from a dropdown list which I have made and on that selection a value be input in to the textbox of the form for eventprice.
So far this is what I have but I have no value being produced in the textbox any help appreciated.
function totalprice(){
if($('#type').val() == '3'){
$('#eventprice') == ("45");
}
}
<input type="text" disabled="" id="eventprice" onChange="totalprice();" name="eventprice" class="form-input" />
If you don't mind using jQuery, it is going to be a breeze: you'll simply need to add the data attribute price to every option. What this function does is:
Compares the value of all options to the value currently visible in the select box when the value is changed.
If the values are the same, copies the data-attribute to the other input.
Working demo: http://jsbin.com/acuyux/6/edit
The HTML
<select id="type">
<option data-price="25">Party</option>
<option data-price="35">Meeting</option>
<option data-price="45">Lounge</option>
</select>
<input type="text" id="eventprice" name="eventprice" disabled="" class="form-input" />
The JS
$('#type').change(function totalprice(){
$('option').each(function() {
if($(this).val() === $('#type').val()) {
$('#eventprice').val($(this).data('price'));
}
});
});
I would recommend using jQuery due to its efficient code.
HTML:
<input type="text" disabled id="eventprice" />
<select id="select">
<option data-cost="5">Event 1</option>
<option data-cost="10">Event 2</option>
</select>
jQuery:
$('#select').change(function () {
var str = $(this).find('option:selected').data('cost');
$('#eventprice').val(str);
});
// This code can be used to run it on load
// $('#select').trigger('change');
Code in action:
http://jsfiddle.net/LkaWn/
Hope this helps :)
Modify the 3rd/4th line of your code to be $('#eventprice').val("45"); as suggested, except that the suggestion had a syntax error.

Sending both the value and key of an option box as parameters?

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>

Drop updating a hiddenfield with an unrelated value

If you wanted to change the value of the hidden field to something not in the value of the dropdown like so
<form>
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="foo">One - 42</option>
<option value="bar">Two - 40</option>
<option value="wig">Three - 38</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>
And i want to pass (if two selected) dropdown="bar" and hiddenInput="40"
The value has to be passed but needs to effect the hiddenfield.
What do you think? Would you need to If then? or could you have it something like
<form>
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="foo" onchange="set hiddenInput - 42">One - 42</option>
<option value="bar" onchange="set hiddenInput - 40">Two - 40</option>
<option value="wig" onchange="set hiddenInput - 38">Three - 38</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>
You have the right idea with the onchange attribute. Your function could look like:
function changeHiddenInput(mySelect) {
var map = {foo: "42", bar: "40", wig: "38"};
var index = mySelect.selectedIndex;
var value = mySelect.options[index].value;
var hiddenInput = document.getElementById("hiddenInput");
hiddenInput.value = map[value];
}
The map variable there maps each option's value on to what the hidden attribute should be set to.
I'd keep the mapping on the server rather then trying to handle it client side.
Forget the hidden input. Just look up the value based on the value of the dropdown after the data reaches the server.
Unfortunately, you'd need the IF statement. You can use the onclick event for the option tags in Firefox and probably other browsers, but in IE you can't set any events on the option elements, only on the select element.

Categories

Resources