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.
Related
IM trying to populate a select field with some data i receive from ajax but the other select the select_dropdow , dont populate and i dont know how to fix it, there someone who could help me with that?
I had some help to mkae the ajax work but now i dont have so im kinda lost i already try to make it with some code from js, but nothing happens in select_dropdow select and i want to populate that select with the data from the data from my sql, like in the image.
index.php
<select id="txt_maq" name="txt_maq">
<option value="">Selecione</option>
<option value="E02">E02</option>
<option value="E03">E03</option>
<option value="E04">E04</option>
<option value="E05">E05</option>
<option value="E06">E06</option>
<option value="E07">E07</option>
<option value="E08">E08</option>
<option value="E04/E07">E04/E07</option>
<option value="E04/E08">E04/E08</option>
<option value="E03/E04">E03/E04</option>
<option value="E03/E07">E03/E07</option>
<option value="E04/E07/E08">E04/E07/E08</option>
<option value="E03/E07/E08">E03/E07/E08</option>
<option value="E07/E08">E07/E08</option>
<option value="E09">E09</option>
</select>
<select id="select_dropdow" name="select_dropdow">
<option value="">Selecione</option>
</select>
<script>
let txt_maq =$("#txt_maq");
let select_dropdow =$("#select_dropdow");
console.log(txt_maq);
console.log(select_dropdow);
txt_maq.on("change", function() {
//faz a consulta no banco com ajax em um
$.ajax({
url: "test.php?maq="+txt_maq.val(),
context: document.body
}).done(function(response) {
console.log(response);
let resposta = JSON.parse(response);
resposta.forEach(function(valor, chave) {
option = new Option(chave, valor);
select_dropdow.options[select_dropdow.options.length] = option;
})
});
});
</script>
test.php
<?php
print_r($_GET);
include ("databaseconfig.php");
$maquina = $_GET["maq"];
$tpe_te = "";
if ($maquina == "E09"){
$type_te= "ET";
} else {
$type_te= "EP";
}
//$tpe_te = $_GET["maq"] === "E09" ? "ET" : "EP";
$consulta = "SELECT Cat_Material FROM cat_mat where TE = '" . $type_te . "' "; //código SQL
$pesquisa = mysqli_query($ligacao,$consulta);
$resultado = [];
while ($listar = mysqli_fetch_array($pesquisa)){
$resultado [$listar['Cat_Material']] = $listar['Cat_Material'];
}
echo json_encode($resultado);
?>
Here is the data when i select the first data in the first select
i want to automatically select value of dropdown matching value of php variable
here is my
<select class="destinationId" id="destination" name="destinationId" onchange="getNationalityAndLiving(this.value,'','');">
<option value="" disabled selected>Select Traveling to</option>
<option data-prefix="azerbaijan" value="azerbaijan" >
Azerbaijan </option>
<option data-prefix="cambodia" value="cambodia" >
Cambodia </option>
<option data-prefix="egypt" value="egypt" >
Egypt </option>
<option data-prefix="india" value="india" >
India </option>
<option data-prefix="kenya" value="kenya" >
Kenya </option>
</select>
<select class="nationality" name="nationality" id="nationality">
<option value="" disabled selected>Select Citizen of</option>
</select>
this is my ajax code to retrive dynamic dropdown for select select option "nationality"
<script>
$(document).ready(function(){
$("#destination").change(function(){
var deptid = $(this).val();
var dbnm = "country";
var res = dbnm.concat(deptid);
$('.overlay').show();
$.ajax({
url: 'getcountry.php',
type: 'post',
data: {dest:res},
dataType: 'json',
success:function(response){
var len = response.length;
$("#nationality").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"'>"+name+"</option>");
}
$('.overlay').hide();
}
});
});
});
</script>
i have some dynamic php variable coming on this page from previous url.
for example
$nationality = "some value";
What i want is selected dropdown with value of $nationality in second dropdown,
if it was static i could have achieved this, but how to auto select in dynamic i am not able to get any workaround.
you can pass the php variable to js variable
var Nationality = "<?php echo $nationality; ?>";
then when append the option you can use
$("#nationality").append("<option data-nation='"+name+"' value='"+name+"' "+ (Nationality.trim() == name.trim()) ? 'selected' : '' +">"+name+"</option>");
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);
}
});
This is my main page where I select a option field.
opt1.php:
<html>
<div>
<select id="mn" onchange = "show(this.id)" >
<option value="3">hello</option>
<option value="4">hiii</option>
<option value="5">byee</option>
</select>
</div>
<?php include 'OPT2.php'?>
</html>
This is my javascript where I get the value from above select and pass to opt2.php
function show(s1){
var s1 = document.getElementById(s1);
var ch = s1.value;
$.post('OPT2.php', {variable: ch});
}
This is my opt2.php page to display the sub select.
<?php
$con = #$_POST['ch'];
echo "SELECT MODEL:<select id=sb name=sb >";
echo "<option name=$con>$con</option>";
echo "</select>";
?>
Actually this is not generating the intended result.
Is there any logical or processing mistake?
you need to make ajax call to opt2.php to get that data
so your opt1.php should look like
<html>
<div>
<select id="s1" onchange = "show(this.id)" >
<option value="3">hello</option>
<option value="4">hiii</option>
<option value="5">byee</option>
</select>
<select id="s2">
<option>--</option>
</select>
</div>
<?php include 'OPT2.php'?>
</html>
and your javascript
<script type="text/javascript">
$("#s1").change(function(){
$('#s2').find('option').remove().end(); //clear the city ddl
var block_no = $(this).find("option:selected").text();
var s1 = document.getElementById(s1);
var ch = s1.value;
//do the ajax call
$.ajax({
url:'OPT2.php',
type:'GET',
data:{variable:s1},
dataType:'json',
cache:false,
success:function(data)
{
//data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('s2');
for(var c=0;c<data.length;c++)
{
var option = document.createElement('option');
option.value = data[c];
option.text = data[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert("Pls Reload the page");
}
});
});
Can anyone help me to populate the select box from web sql. I am creating an offline mobile app. So I have two select boxes one for category and other for level. When the user selects the category corresponding level has to appear in the select box. As I am new to web sql I need some help to get the corresponding level from web sql based on the category selected in the first drop down box.Thanks in advance.
$(document).ready(function(){
$('#category').on('change',function(){
var cat = document.getElementById('category').value;
alert(cat);
db.transaction(function (tx) {
//alert("SELECT levell FROM level WHERE category="+cat);
tx.executeSql('SELECT levell FROM level WHERE category='+cat, [category], function (tx,results) {
alert("hello");
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
editRecords2(row.lev_id,row.levell);
}
});
});
});
});
function editRecords2(lev_id,levell) {
f = $('#level');
f.html("");
f.html(f.html() + '<option value='+lev_id+'>'+levell+'</option>');
}
html:
<select id='category' required>
<option value='' disabled selected>Select your category</option>
<option id='c1'>Category 1</option>
<option id='c2'>Category 2</option>
<option id='c3'>Category 3</option>
<option id='c4'>Category 4</option>
<option id='c5'>Category 5</option>
<option id='c6'>Category 6</option>
</select>
<select id="level">
<option value="">Select your level</option>
</select>
Assuming you have a country table set up in your database here is a working example on Chrome.
<script type="text/javascript" src="../assets/js/jquery.min.js"> </script>
<script type="text/javascript">
var errCallback = function(){
alert("Database Error!");
}
// initialise the db - this will fail in browsers like Firefox & IE
var db = openDatabase("local_customers", "0.1", "myData", 65536);
db.transaction(
function(transaction) {
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS customers (user_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, country_id TEXT);'
);
});
// This is the SAVE function
var saveCustomers = function(user_id, country_id, successCallback){
db.transaction(function(transaction){
transaction.executeSql(("INSERT INTO customers (user_id, country_id) VALUES (?, ?);"),
[user_id, country_id], function(transaction, results){successCallback(results);}, errCallback);
});
};
// Document ready event.
$(function(){
var form = $("form");
db.transaction(function (tx) {
tx.executeSql('select * from country', [], function (tx, results){
var len = results.rows.length, i;
var html = "<select name=\"country_id\">";
for (i = 0; i < len; i++) {
html += "<option value='" + results.rows.item(i).country_id + "'>" + results.rows.item(i).country + "</option>";
}
html += "</select>";
var el = document.getElementById("country_id");
el.innerHTML = html;
});
});
// Override the default form submit in favour of our code
form.submit(function(event){
event.preventDefault();
saveCustomers($('#user_id').val(), $('#country_id').val(), function(){
alert($('#country_id').val() + " has been added.");
})
});
});
<!--HTML is here & just using a dummy input for user_id here-->
<form>
<input type="text" id="user_id" name="user_id" class="user_id" value = "2" hidden />
<p><select type="text" id="country_id" name="country_id" class="country_id" >Select Country</select></p>
<p><input type="submit" value="Add Country" /></p>
</form>