Generate Dynamic Select List Item Menu using JQuery
Here is the Div :
<select name="CountryID" id="CountryID">
<option value="" id="">Select the Country</option>
......
</option>
</select>
<div id='result' name="result">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
</div>
<div id='resulta' name="resulta">
<select id="name">
<option value="" disabled>Please select above</option>
</select>
</div>
Here is my Script :
<script>
var ab=$.noConflict();
ab(document).ready(function(){
ab("#CountryID").change(function(){
var CountryID=ab("#CountryID").val();
ab.post("globalregiongenerator",
{
CountryID:CountryID
},
function(data,status){
ab( "#result" ).html( data );
});
});
});
</script>
<script>
var ac=$.noConflict();
ac(document).ready(function(){
ac("#RegionName").change(function(){
//alert('action triggered');
var RegionName=ab("#RegionName").val();
ac.post("globalcitygenerator",
{
RegionName:RegionName
},
function(data,status){
ac( "#resulta" ).html( data );
});
});
});
</script>
Here i generate my Select Menu List
public function globalregiongenerator()
{
$CountryID = Input::get('CountryID');
$roles = DB::table('region')->where('CountryID', $CountryID)->lists('regionname','regionid');
echo "<select id='RegionName' name='RegionName'>";
foreach ($roles as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
}
public function globalcitygenerator()
{
$RegionName = Input::get('RegionName');
$roles = DB::table('city')->where('RegionName', $RegionName)->lists('regionname','regionid');
echo "<select id='CityName' name='CityName'>";
foreach ($roles as $value)
{
echo "<option value=".$value.">".$value."</option>";
}
}
I can able to generate the First Select Menu List Item, But the action ac("#RegionName").change(function(){ is not triggering, even i tried putting alert inside it.
Is the Second List Menu Item <select id='RegionName' name='RegionName'> not creating in the page or what.
How can i do this ?
Note :
I even tried ab('#RegionName').selectmenu('refresh', true); under the ab( "#result" ).html(data); from this answer but it didn't worked
Update :
If we append $( "#result" ).append ( data ); another menu will appear, that isn't i need.
I need to the first three menu already there.
Looks like you're not closing <select, I think you need echo </select> as well. For the handler try
ac(document).on("click", "#RegionName"
You also have a var RegionName=ab("#RegionName").val(); which should be var RegionName=ac("#RegionName").val();
update:
line should be
RegionName=ac(this).val();
Update2
Change
echo "<option value=".$value.">".$value."</option>";
to
echo "<option value='".$value."'>".$value."</option>";
For dynamic elements we should use delegated events:
Change ac("#RegionName").change(function(){ /* handler body */ })
To ac(document).on("change","#RegionName",function(){ /* handler body */ })
Also Change ab("#CountryID").change(function(){ /* handler body */ })
To ab(document).on("change","#CountryID",function(){ /* handler body */ })
To get selected value, you can do like below within the function
ab(document).on("change","#CountryID",function(){
var countryId = ab(this).val();
//or like => var countryId = ab(":selected", this).val();
/* Rest of code */
})
Correct below statement in server side you have to enclose value in quotes
echo "<option value='".$value."'>".$value."</option>";
Related
I made a similar question yesterday, but couldn't come up with a solution since then, so i went and refined my code a bit to a logic that seemed more plausible to work.
However, it didn't.
I want to have only a couple of options in a combobox available to the user, depending on what option was pre-selected. Here is the Combobox:
<SELECT class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus onchange= "StatusTest(); hideField();" >
<option selected></option>
<option value="Planned" id="optionPlanned" <?php if ($row['task_status']=='Planned') echo 'selected="selected"';?>>Planned</option>
<option value="Started" id="Started" <?php if ($row['task_status']=='Started') echo 'selected="selected"';?>>Started</option>
<option value="Available" id="Available" <?php if ($row['task_status']=='Available') echo 'selected="selected"';?>>Available</option>
<option value="Finished" id="Finished" <?php if ($row['task_status']=='Finished') echo 'selected="selected"';?>>Finished</option>
<option value="Impeded" id="Impeded" <?php if ($row['task_status']=='Impeded') echo 'selected="selected"';?>>Impeded</option>
</SELECT>
For example, when "Planned" is selected, the only other available option should be "Started". So i went and made a Javascript, for a Onchange Event, like so:
function hideField(){
var e = document.getElementById("cbostatus");
var strUser = e.options[e.selectedIndex].value;
if( strUser == 'Planned' ) {
document.getElementById("Impeded").style.display = 'none';
document.getElementById("Available").style.display = 'none';
document.getElementById("Finished").style.display = 'none';
}
}
And for some reason, it is wrong. Any ideas?
(Also, i'd aprecciate if you didn't suggest using Jquery, as i have never used before and don't really have time to learn for this)
I suggest you start with an empty select, and add the options dynamically.
var e=document.getElementById("cbostatus");
var strUser = 'Planned'; // get this value from somewhere, maybe a hidden field
if( strUser == 'Planned' ) {
e.options[e.length]=new Option("Planned", "optionPlanned", true, true);
e.options[e.length]=new Option("Started", "Started");
} else if ..
Use this code.
Html
<select class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus>
<option selected></option>
</select>
jQuery
var insertoption = "";
first add options in ready function
$(document).ready(function()
{
insertoption += "<option value='Planned' id='Planned'>Planned</option>";
insertoption += "<option value='Started' id='Started'>Started</option>";
insertoption += "<option value='Available' id='Available'>Available</option>";
insertoption += "<option value='Finished' id='Finished'>Finished</option>";
insertoption += "<option value='Impeded' id='Impeded'>Impeded</option>";
$("#cbostatus").append(insertoption);
insertoption = "";
});
This is create your option
and now create onchange function
$("#cbostatus").on("change",function()
{
if($("#cbostatus").val() == "Planned")
{
$("#cbostatus").children().remove();
insertoption = "<option value='Started' id='Started'>Started</option>";
$("#cbostatus").append(insertoption);
}
});
I get users from mysql query. I show this users into table and add a HTML into php file to all users to change a value:
...
do {
echo "<td > <a>".$row["username"]."</a> </td> \n";
echo "<td > <a>".$row["name"]."</a> </td> \n";
echo "<td > <select id='sel'> <option value='admin'>Admin</option> <option value='user'>User</option> </select> </td> \n";
} while ($row = mysql_fetch_array($result));
echo "</tbody></table> \n";
...
How can I get the option selected??
I'm trying get this in javascript but always get the same first value, independet value selected.
function myFunction() {
var e = document.getElementById("sel");
var strUser = e.options[e.selectedIndex].value;
}
Thanks!
Use the jquery .change function.
Fiddle :- https://jsfiddle.net/a2abaL44/1/
<script type="text/javascript">
$("#sel").change(function(){
var selectVal = $(this).val();
})
</script>
https://api.jquery.com/change/
Because your loop will be executed multiple times (once for each user in the database), you will have many <select> elements with the same ID. You cannot have the same ID given to many different elements, and this is why your JavaScript is only returning the value of the first <select>.
If you tell me what you are needing the selected value for, I can update the answer further.
Your code is fine, Change your select to <select id="sel" onchange="myFunction();">
<script type="text/javascript">
function myFunction() {
var e = document.getElementById("sel");
var strUser = e.options[e.selectedIndex].value;
alert(strUser);
}
</script>
I have an ajax dynamic dropdown form that onchange changes a second dropdown based on the firsts selection. However, if someone were to reset the form, all elements get cleared except for the dynamic one.
I made a reset button function that does: $('#myForm')[0].reset();
However it doesn't reset the dynamic dropdown.
Then I added $('#state').prop('selectedIndex',0); which only then selects the initial subitem.
Essentially I want it to go back to the default <option value="">State/Province</option> state that was there prior to becoming dynamic and I cannot figure out how to exactly to do this.
I am very very new and used previous questions and google to even get me this far.
Thanks
Update:
This is what I need reset:
<select name="state" class="dropdown" id="state">
<option value="">State/Province</option>
<!-- this is populated by ajax -->
</select>
This form changes the above:
<select name="country" class="dropdown" id="country" onchange="getStates();">
<option value="">Select Country</option>
<?php
$con = mysql_connect($db_host, $db_user, $db_pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('earth');
$query = "select id,country from regions order by country";
$result = mysql_query($query);
while ( $row = mysql_fetch_object( $result ) )
{
?>
<option value=<?php echo $row->id; ?>><?php echo $row->country;?> </option>
<?php }
mysql_free_result($result);
?>
</select>
Additional code:
function getStates()
{
$('#state').html('');
var e = document.getElementById("country");
var countryID = e.options[e.selectedIndex].value;
$.ajax({
type: "POST",
url: "getStates.php",
data: {countryID:countryID},
dataType:'json',
//success: function(result){
success: function(data){
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option value=' +o.id + '>' + o.name + '</option>';
});
$('#state').append(toAppend);
},
});
}
function reset_select_box(selector, default_value)
{
if(typeof default_value !== 'string') default_value = "";
var select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
function resetForm()
{
// since the form is dynamic, reset form does not reset the states
$('#frmSigGen')[0].reset();
}
This seems to do the trick:
function resetForm()
{
$('#frmSigGen')[0].reset();
$('#state').empty();
$('#state').append('<option value="">State/Province</option');
}
Maybe try looping through the select elements children looking for the default value?
var reset_select_box = function(selector, default_value){
if(typeof default_value !== 'string') default_value = "";
var
select_box = $(document).find(selector),
children = select_box.children();
console.log(children);
for(var i in children){
if(children[i].value === ""){
select_box.prop('selectedIndex', i);
}
}
};
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<select id="test">
<option value="">Default</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5</option>
</select>
<button type="button" onclick="reset_select_box('#test');">Reset</button>
</body>
</html>
You could mark the newests options adding a particular data tag, i.e. data-toreset. Then, when you need to reset, remove only options with that tag.
The newest options:
<option data-toreset="1"></option>
The JQuery script could be like:
$('*[data-toreset="1"]').remove();
And then you could select the first element of your combo.
I'm having a problem with filtering HTML select options witch are based html input. For example:
If i write t-shirt in my input i want to see only T-shirts in my select options
My code looks like this...
<input type="text" name="search" id="inputdata" onkeyup="filter()">
<select name="select[]" id="filtersimilar" multiple>
<?php foreach ($all as $row) { ?>
<option value="<?php echo $row->id_product; ?>" itemid="<?php echo $row->name; ?>"><?php echo $row->name; ?></option>
<?php } ?>
</select>
And JS / Jquery code is:
<script>
function filter(){
inp = $('#inputdata').val();
$("#filtersimilar").change(function() {
var options = $(this).data('options').filter('[itemid=' + inp + ']');
$('#select2').html(options);
});
}
</script>
Have you checked jquery.filter documentation? (http://api.jquery.com/filter/) As #Elfentech pointed out, your referring to something that does not exist (options).
I recommend you make all options invisible with "style="display:none;", and when you do the filtering give the filtered options a "display:block;". But still, your filter method looks really out of standard. Check the documentation to understand how filtering works.
Right answer for me was this one
$(function() {
var opts = $('#filtersimilar option').map(function(){
return [[this.value, $(this).text()]];
});
$('#inputdata').keyup(function(){
var rxp = new RegExp($('#inputdata').val(), 'i');
var optlist = $('#filtersimilar').empty();
opts.each(function(){
if (rxp.test(this[1])) {
optlist.append($('<option/>').attr('value', this[0]).text(this[1]));
}
});
});
});
When I click the category for the License, nothing happens.
<script>
function goToPage( select1 ) {
var node = document.getElementById( select1 );
if( node &&
node.tagName == "SELECT" ) {
// Go to web page defined by the VALUE attribute of the OPTION element
window.location.href = node.options[node.selectedIndex].value;
} // endif
}
</script>
<center><label for="select1">Go to Marker</label></center>
<select id="select1" onChange="goToPage('select1')">
<?php
$conn=mysql_connect("localhost","root","");
mysql_select_db("dbposo",$conn);
$news=mysql_query("select id,license from tblviolator");
while($data=mysql_fetch_array($news))
{
$id=$data['id'];
$license=$data['license'];
print "
<option value='#X$id'>$license</option>
";
}
?>
</select>
you can simply write your select tag as follows without calling the function. if you only want to redirect on the value of your select box
<select id="select1" onChange="window.location.href=this.value;">
UPDATE 2:
<script>
var current_url = window.location.href ;
function goToPage(val) {
window.location.href = current_url+val;
}
</script>
<select id="select1" onChange="goToPage(this.value);">