How can I change variable inside jQuery function to make possible read it outside, for example print it to html.
Becouse when I tried to change select option content of debug div didn't change.
Why doesn't it work?
My code:
$(document).ready(function() {
var day;
var month;
var year;
$('#day').change(function() {
day = true;
});
$('#month').change(function() {
month = true;
});
$('#year').change(function() {
year = true;
});
document.getElementById('debug').innerHTML = day + month + year;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="input-group">
<select class="custom-select" id="den">
<option value="Den" disabled selected hidden>Den</option>
<?php foreach ($datum['dny'] as $dny) : ?>
<option value="<?= $dny ?>"><?= $dny ?></option>
<?php endforeach ?>
</select>
<select class="custom-select" id="mesic">
<option value="Měsíc" disabled selected hidden>Měsíc</option>
<?php foreach ($datum['mesice'] as $cislo => $nazev) : ?>
<option value="<?= $cislo ?>"><?= $nazev ?></option>
<?php endforeach ?>
</select>
<select class="custom-select" id="rok">
<option value="Rok" disabled selected hidden>Rok</option>
<?php foreach ($datum['roky'] as $roky) : ?>
<option value="<?= $roky ?>"><?= $roky ?></option>
<?php endforeach ?>
</select>
</div>
DEBUG:
<div id="debug">
</div>
Thank you for your helps.
You need to have each function check to see if all the vars are filled out, and then set the content if so.
Use a separate function to keep it short.
$(document).ready(function() {
var day;
var month;
var year;
$('#day').change(function() {
day = this.value;
check();
});
$('#month').change(function() {
month = this.value;
check();
});
$('#year').change(function() {
year = this.value;
check();
});
function check() {
if (day && month && year) {
document.getElementById('debug').innerHTML = `${day}-${month}-${year}`;
}
}
});
pre {
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Day
<select id=day><option>
<option>1 <option>2 <option>3
</select> Month
<select id=month><option>
<option>1 <option>2 <option>3
</select> Year
<select id=year><option>
<option>2018 <option>2019 <option>2020
</select>
<pre id=debug></pre>
When I am select dropdown option then does'not assign the value of selected option in hidden field.
Please correct Where I am doing wrong. Thanks in advance.
<?php
include("../common/config.php");
$time = time();
$id=$_REQUEST['dr_id'];
$allEst = $db->select(array("*"),PREFIX."obligation_pharmacy","obligation_id IN ($id)");
}
?>
<script type="text/javascript">
function populate(unique,sel){
alert(sel.value);
$("#pharmacy_id"+unique).val(sel.value);
}
</script>
<select name="pharmacy_name[]" class="name" id="pharmacy_name<?php echo $time?>" style="width:180px; font-size:11px;" onchange="populate(<?php echo $time?>,this)">
<option value="">Select Pharmacy Name</option>
<?php
foreach($allEst as $ss)
{if($ss->pharmacy_name!=''){?>
<option value="<?php echo $ss->id;?>"><?php echo $ss->pharmacy_name; ?></option>
<?php }} ?>
</select>
<input type="hidden" name="pharmacy_id[]" id="pharmacy_id<?php echo $time?>" value="">
Using jQuery, usually something like this:
$('#my-select').change(function(){
var value = $(this).val();
$('#my-hidden-input').val(value);
});
$('#pharmacy_name').change(function(){
// get selected option value
var option_val = $( "#pharmacy_name option:selected" ).val();
// populate hidden field
$('#pharmacy_id').val(option_val);
}
is there an easy way to update an html property from an HTML select object ? in the example below I would like to update name with the value from the select object when the user chooses an option.
EDIT: user can add more search criteria like below; I have a function to add similar code like below to the search form.
<input id="AS1" class="searchCriteriaInput" type="text" name="" value="" />
<select>
<?php
foreach ($fields as $key => $value) {
if ($key=="select") {
echo "<option selected value='".$key."'>".$value."</option>";
} else {
echo "<option value='".$key."'>".$value."</option>";
}
}
?>
</select>
This does what you ask, although it is not impressive to look at in the snippet, however, inspecting the input field after change shows that the name attribute has been populated.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="AS1" class="searchCriteriaInput" type="text" name="" value="" />
<select onChange="doThing(this)">
<option value="KeyOne">ValOne</option>
<option value="Key2">Val2</option>
<option value="Key3">Val3</option>
<option value="Key4">Val4</option>
<option value="Key5">Val5</option>
</select>
<script type="text/javascript">
function doThing(f){
$("#AS1").attr("name",$(f).val());
}
</script>
You can use jquery. Bind the on change event for select and set select value to required place. for your example
<input id="AS1" class="searchCriteriaInput" type="text" name="" value="" />
<select class="sel">
<?php
foreach ($fields as $key => $value) {
if($key=="select"){
echo "<option selected value='".$key."'>".$value."</option>";
}else{
echo "<option value='".$key."'>".$value."</option>";
}
};
?>
</select>
$(document).ready(function(){
$('.sel').change(function(){
var value = $(this).val();
$('#AS1').val(value);
});
})
Don't forget to add jquery library
You don't need php for it. You can do it using javascript (Jquery). Here's an example:
$(document).ready(function() {
$("#select_name option").filter(function() {
return $(this).val() == $("#animal_name").val();
}).attr('selected', true);
$("#select_name").on("change", function() {
$("#animal_name").attr("name",$(this).find("option:selected").attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_name" name="select_name">
<option value="">Please select an animal</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
<input type="text" id="animal_name" name="animal_name" value="" readonly="readonly">
I have 2 different SELECT OPTION in a form.
The first one is Source, the second one is Status. I would like to have different OPTIONS in my Status drop-down list depending on the OPTION selected in my Source drop-down.
Source:
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
Status:
<select id="status" name="status">
</select>
Options:
- If Source is MANUAL, then Status is OPEN or DELIVERED
- If Source is ONLINE, then Status is OPEN or DELIVERED or SHIPPED
My non-working attempt:
<script>
$(document).ready(function () {
var option = document.getElementById("status").options;
if (document.getElementById('source').value == "MANUAL") {
$("#status").append('<option>OPEN</option>');
$("#status").append('<option>DELIVERED</option>');
}
if (document.getElementById('source').value == "ONLINE") {
$("#status").append('<option>OPEN</option>');
$("#status").append('<option>DELIVERED</option>');
$("#status").append('<option>SHIPPED</option>');
}
});
</script>
Try something like this... jsfiddle demo
HTML
<!-- Source: -->
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
<!-- Status: -->
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
</select>
JS
$(document).on('ready', function () {
$("#source").on('change', function () {
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
switch (listindex)
{
case "manual" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
break;
case "online" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Source:
<select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select source</option>
<option value="manual">MANUAL</option>
<option value="online">ONLINE</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Status:
<script type="text/javascript" language="JavaScript">
document.write('<select name="status" id="status"><option value="">Select status</option></select>')
</script>
<noscript>
<select id="status" name="status">
<option value="open">OPEN</option>
<option value="delivered">DELIVERED</option>
</select>
</noscript>
</div>
</body>
</html>
For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list
function dropdownlist(listindex)
{
document.getElementById("ddlCity").options.length = 0;
switch (listindex)
{
case "Karnataka":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");
break;
case "Tamilnadu":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");
break;
}
}
*
State:
--Select--
Karnataka
Tamilnadu
Andra pradesh
Telngana
<div>
<p>
<label id="lblCt">
<span class="red">*</span>
City:</label>
<select id="ddlCity">
<!-- <option>--Select--</option>
<option value="1">Dharawad</option>
<option value="2">Belgum</option>
<option value="3">Bagalkot</option>
<option value="4">Haveri</option>
<option>Hydrabadh</option>
<option>Vijat vada</option>-->
</select>
<label id="lblCity"></label>
</p>
</div>
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
You're better off making two selects and showing one while hiding the other.
It's easier, and adding options to selects with your method will not work in IE8 (if you care).
I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.
HTML DYNAMIC DEPENDENT SELECT
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
GETTING STATES VIA AJAX
<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});} </script>
READ STATE DATABASE USING PHP
<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>
for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.
The answer should be updated to replace the defunct functions .change & .ready
$(document).on('ready',function() {
$("#source").on('change', function(){
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
I'm trying to send the selected option text to the url using jquery but whenever I wrap my form between <form></form> tags it stops working and sends the value instead of the text. If I remove the form tags it behaves the way i expect.
I want to know if there's any way to make it work without excluding the form tags
Thanks!
<form>
<select name="brand" id="brand" class="update">
<option value="">Seleccionar</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="model" id="model" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="size" id="size" class="update" disabled="disabled">
<option value="">----</option>
</select>
<input type="submit" value="Search" id="submit">
</form>
</div>
</div>
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="js/core.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var brand = $('#brand option:selected').text();
var model = $('#model option:selected').text();
var size = $('#size option:selected').text();
location.href ='index.php?s='+brand+'+'+model+'+'+size+'';
});
});
</script>
The form is submitting, you'll need to prevent that:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var brand = $('#brand option:selected').text();
var model = $('#model option:selected').text();
var size = $('#size option:selected').text();
location.href ='index.php?s='+brand+'+'+model+'+'+size+'';
});
});
You need to return false from your event handler to prevent the form submission from taking place.
Just add
return false;
at the end. (You can also do what adeneo's answer says to do; either should work.)