I have this form where there is one select element originally but the user can add the number of select when clicking on 'add'. Then when the user submitted the form, and there are some invalid input (i.e unfilled input) the form is not submitted ( I am using php for form validation), and it goes back to the original page with only 1 select displayed, so I use jquery and count the array of the select submitted and append the select elements as much as the user chosen at first. Now the problem is how do I set the value of the appended select to be the value that the user has chosen ?
Sorry for the bad explanation, here is the code, hope it helps giving a clearer picture :
html
<div class='select_container'>
<select name='select[]'>
<option value='option1'>Option1</option>
<option value='option2'>Option2</option>
<option value='option3'>Option3</option>
</select>
</div>
<div class='add'>Add</div>
JQuery
$(document).ready(function() {
//User can add more select element by clicking 'add'
$('.add').click(function() {
$('<select name="select[]">' +
'<option value="option1">Option1</option>' +
'<option value="option2">Option2</option>' +
'<option value="option3">Option3</option>' +
'</select>').appendTo('.select_container');
});
//When form failed to submit(i.e invalid input), automatically
//add the select element as many as the user added at first
//get the user select input, make it into array
var select = "<?php $select= echo implode(',',$_POST['select']); ?>";
var select_array = select.split(',');
var select_length = select_array.length;
//after counting length of array, add the amount of select element the user added
for (i = 1; i < select_length; i++) {
$('<select name="select[]">' +
'<option value="option1">Option1</option>' +
'<option value="option2">Option2</option>' +
'<option value="option3">Option3</option>' +
'</select>').appendTo('.select_container');
}
});
I managed to append the select element so that when form failed to submit, user did not have to re-add the select element, and I want the appended select element when the form failed to submit to automatically set to the value that the user chosen.
I have tried delegate(), on() and a bunch of other stuff, but I am still unable to set the value of the appended select elements. I was only able to set the value of the original first select in the html.
Please if anyone knows a way to set the value of the appended select, all answers and suggestions are greatly welcomed and appreciated.
Thanks
You can do something like this (I'm assuming you post the form back to the same file):
// if reloaded after post basically
if( select.length > 0 ) {
// if there are multiple groups of selects, add class and call each on that
$('select').each(function(i) {
$(this).val( select_array[i] );
});
}
The order of the selects are guaranteed due to the linear nature of the form processing, so that should't be a problem.
Assuming that options stay same, You may do it simply by submitting the form to the same page(current page) and In your php file, html part should look like this
<div class='select_container'>
<select name='select[]'>
<option value='option1'>Option1</option>
<option value='option2'>Option2</option>
<option value='option3'>Option3</option>
</select>
<?php
if(!isset($_POST)&&!empty($_POST['select'])){
for($i=0;$i<sizeof($_POST['select']);$i++){
echo '<select>';
$options=array('option1','option2','option3');
for($j=0;$j<sizeof($options)){
if($options[$j]==$_POST['select'][$i]){
echo '<option
value="'.$options[$j].'"
selected="selected">'.$options[$j].'</option>';
}else{
echo '<option
value="'.$options[$j].'">'.$options[$j].'</option>';
}
}
echo '</select>';
}
}
?>
</div>
<div class='add'>Add</div>
Related
I have a checkbox and a select option on my page that displays data from my database.
I want a situation where when a user checks the checkbox,then the word "All" will be displayed in the select option and all data displayed on table. Then when a user selects any option from the drop-down,the checkbox should be unchecked and the corresponding rows of data displayed as selected by user.
I'm still learning my way through with JavaScript and jQuery. I know its solution lies there but I don't know just how to get about it. Below is what I've tried following similar cases but it hasn't solved my problem.
My html for the check box and select
<input type="checkbox" name="check" id="check" onchange="this.form.submit();"/>Show All
<select id="rowno" name="rowno" onchange="this.form.submit();">
<option value"10"<?php if(isset($_POST['rowno']) && $_POST['rowno']=="10") echo "selected";?>>10</option>
<option value"20"<?php if(isset($_POST['rowno']) && $_POST['rowno']=="20") echo "selected";?>>20</option>
<option value"30"<?php if(isset($_POST['rowno']) && $_POST['rowno']=="30") echo "selected";?>>30</option>
<option value"40"<?php if(isset($_POST['rowno']) && $_POST['rowno']=="40") echo "selected";?>>40</option>
</select>
Below is the jquery code:
<script type="text/javascript>
//js code to persist checkbox state using local storage
function onClickBox()
{
let checked = $("#check").is(":checked");
localStorage.setItem("checked", checked)
if($("#check").is(":checked"))
{
//code to re-populate select on checkbox checked
if(this.checked)
{
var select = $("#rowno");
select.empty();
var options = "";
options += "<option hidden>All</option>";
options += "<option value = '10' >10</option>";
options += "<option value = '20' >20</option>";
options += "<option value = '30' >30</option>";
options += "<option value = '40' >40</option>";
select.html(options);
}
else
{
var select = $("#rowno");
select.empty();
var options = "";
options += "<option value = '10' >10</option>";
options += "<option value = '20' >20</option>";
options += "<option value = '30' >30</option>";
options += "<option value = '40' >40</option>";
select.html(options);
}
return confirm('Are you sure you want to display all rows? For a large table, this might crash the browser.');
}
}
function onReady()
{
let checked = "true" == localStorage.getItem("checked");
$("#check").prop('checked', checked);
$("#check").click(onClickBox);
}
$(document).ready(onReady);
//code to uncheck checkbox when select option selected
$("#rowno").change(function()
{
let selected = $("#rowno").is(":selected");
localStorage.setItem("selected", selected);
select = localStorage.getItem("selected");
if(select)
{
$("#check").prop('checked', false);
}
});
</script>
Perhaps the following MIGHT help a little - though I notice you have added some Javascript which uses localStorage to maintain checkbox checked state seeminly which was not specified in the original code/question.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<!-- the form should have a name for easy reference to it in javascript -->
<form method='post' name='geronimo'>
<input type='checkbox' name='check' value=1 />Show All
<select name='rowno'>
<option value='all' hidden disabled>All
<option value='10'>10
<option value='20'>20
<option value='30'>30
<option value='40'>40
</select>
<input type='submit' />
</form>
<?php
/*
This is ONLY to show what has been submitted
by the form - for reference only... though you
could query the database here.
*/
if( !empty( $_POST ) ){
printf('<pre>%s</pre>',print_r($_POST,true));
}
?>
<script>
<?php
/*
Using PHP to create a javascript variable that can be used to
add the `selected` attribte to the respective option is much
cleaner and easier than potentially hundreds of inline PHP echo
statements as per the original code. imho
*/
printf(" /* Dynamic variable from POSTed data - OR Zero! */
let rownum='%s';
\n\n", !empty( $_POST['rowno'] ) ? $_POST['rowno'] : 0 );
?>
let oForm=document.forms.geronimo;
let oSel=oForm.rowno;
let oChk=oForm.check;
// find all options and if the POSTed value matches - add the selected attribute
// establish initial display conditions following page load / form submission
if( rownum ){
if( rownum=='all' )oChk.checked=true;
Array.from( oSel.querySelectorAll('option') ).some(option=>{
if( rownum==Number( option.value ) || rownum=='all' ){
option.selected=true;
return true;
}
});
}
// listen for changes on the checkbox
oChk.addEventListener('click',function(e){
if( oSel.firstElementChild.value=='all' ){
oSel.firstElementChild.selected=this.checked;
oSel.firstElementChild.disabled=!this.checked;
}
});
oSel.addEventListener('change',function(e){
if( oChk.checked )oChk.checked=false;
alert(
'The checking/unchecking of elements and selection of the hidden "All" ' +
'option are done. What is NOT done is the selection of records from the database.\n\n' +
'Currently the approach seems to be using regular form submissions rather than AJAX,\n'+
'which is why once this dialog closes the form will be submitted...\n\nGood luck.'
);
oForm.submit();
});
</script>
</body>
</html>
Notes on the identified portion of code
/*
OK - we have `rownum` which is created by PHP and is based upon
previous form submission ( in this version )
`rownum` will either be an integer (10,20,30..etc ) as it's value
comes from the dropdown or, if the checkbox is checked, the value
will be "all"
If the value is "all" we should ensure that the checkbox is ticked.
Array.from will, in this case, convert a `nodelist` into an array -
which we want to do if we want to use certain native array methods, such
as `forEach` or, in this case, `some`. There are others we could use -
Array.prototype.map for instance.
According to MDN:
"NodeList objects are collections of nodes, usually returned by properties
such as Node.childNodes and methods such as document.querySelectorAll()."
So - using `querySelectorAll` we return a `static nodelist` which we convert
to an array and then iterate through. The `some` method can be cancelled if
some logic test evaluates as true within the loop. This is useful as it means
we do not need to process ALL nodes/array items. The logic test used here
simply tests whether or not the current array item value( which is the option.value )
is the same as the rownum variable or "all" - if it is the logic test is true
so we can stop further processing and perform whatever operations we want to.
In this case we want to ensure that the respective option in the select menu is
set as "selected" and then we return true to cancel the `some` loop.
*/
if( rownum ){
if( rownum=='all' )oChk.checked=true;
Array.from( oSel.querySelectorAll('option') ).some(option=>{
if( rownum==Number( option.value ) || rownum=='all' ){
option.selected=true;
return true;
}
});
}
As i mention on the question, i want to update one select box if another value in the another select box is selected.
for example:
<select id="makale" size="4"name="formMakale"style="height:7em;width:16em;border:0px;outline:0px;font-size:16px;padding-left:10px;" >
<?php
$authorsQuery = $hb->authors();
foreach($authorsQuery as $v){
echo '<option value="'.$v->id.'">'.$v->name.'-'.count($hb>aticlesbyauthor($v),1000).' yazi</option>';}
?>
</select>
<select id="kategoriSec" size="4" name="formCat"style="height:7em;width:16em;border:0px;outline:0px;fontsize:16px;padding-left:10px;" >
<?php
$catQuery = $hb->db->get_results("SELECT * FROM category");
foreach ($catQuery as $v) {
echo '<option value="'.$v->id.'">'.$v->name.'</option>';
}
?>
if i select something from this select box with id makale, i want to update the options of the select box with id kategorisec.
can you help me?
Thank you.
If you just want to change it on the browsers side, use the onchange event handler.
If you want to update the checkboxes based on server data, you could use ajax or simply use an iframe:
<input onclick="update(this)">
<iframe src="checkboxes.php">Oh ,update your browser</iframe>
<script>
function update(elem){
if(elem.selected){ iframe=document.getElementsByTagName("iframe")[0]
iframe.src="checkboxes.php?select="+elem.value;
}
}
</script>
It's my first time i ask a question here. i'm stuck here, so i hope someone can solved this problem. thanks :)
I have some php code that i want to made a input select option adding automaticallly when clicked a button in my form. i mean, when the user clicked the button 3 times, so there are 3 input select options:
it was working when i have using with this javascript code:
var counter = 1;
var limit = 30;
function addInput(divName){
var kdprov= $("#provinsi_id").val();
if (counter == limit) {
alert("Maksimal input ialah " + counter + " sekolah");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div><span class='input-group-addon' ><b> Sekolah ke-"+ (counter + 1)+"</span></b><select class='form-control' name='npsn"+
(counter + 1)+"' ><option value='' disabled selected>--Pilih Sekolah--</option>'.<?php foreach($sekolah as $sekolah1){ ?>'<option value='<?php echo $sekolah1->npsn;?>' ><?php echo $sekolah1->nama_sekolah; ?></option><?php } ?>.'</select></select></div>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
And this html code:
<input type="button" value="Tambah Sekolah" onClick="addInput('sekolah');"> </br></br>
but, the problem. they are retrieved all of variable $sekolah in database because i only used SELECT * FROM Sekolah in sql code.
And now I want to made a query SELECT * FROM Sekolah where provinsi=$provinsi
in my select option. but, the other problem is variable $provinsi got from javascricpt value. I mean,it is a chained dropdown. when i choose a option from $provinsi, so i want #sekolah option will retrieve only from the selected $provinsi option.
It worked in only static input, but i can't used it in my dimanic input select option.
So, what should i do? I'm not really understand about javascript, so can someone give me the solution? i made it in codeIgniter.
can i use a query in php code to get data from database in javascript?
Here is an example of how I would do this. I would create the select menu on load, so there is always one available. Then I would clone that select element whenever the button is clicked. See the example below.
Working example:
https://jsfiddle.net/tkfc031h/1
HTML
<div id="theSelectElements">
<label class="foo">Number <span>1</span>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>
</label>
</div>
<button id="addOne">One more</button>
jQuery
$('#addOne').click(function(){
var theSelect = $('.foo:last-child').clone();
var count = (parseInt(theSelect.find('span').text()) + 1);
theSelect.find('span').html(count);
theSelect.find('select').attr('name', "select"+count)
$('#theSelectElements').append(theSelect);
})
First of all, let me clarify what you want.
You have a dropdown "Provinsi" contains for example:
Aceh
Sumatera Utara
Riau & Kepri
And you have a button "Tambah Sekolah".
You select "Sumatera Utara" then click "Tambah Sekolah", you will have a new dropdown "Sekolah", contains for example:
sekolah sumut 1
sekolah sumut 2
sekolah sumut 3
You select "Riau & Kepri" then click "Tambah Sekolah", you will have another new dropdown "Sekolah", contains for example:
sekolah riau 1
sekolah riau 2
sekolah riau 3
If the above requirements is what you want, then you should use ajax too. Here what you need to do:
Collect the value of selected "province" by using javascript
Send "province" by using ajax to a page in server-side
A page in server-side, query the database for list of school filterd by "province" (SELECT * FROM sekolah WHERE provinsi = ?), then return the list of values to be shown in dropdown
After ajax request has been completed, create a new dropdown with values from previous ajax response
In this example: https://jsfiddle.net/o0s1L4k1/, see what happen if "Tambah Sekolah" button is clicked:
$.ajax({
method: 'POST',
url: 'list-sekolah.php', // page that will query schools by province
data: {
provinsi: $('#provinsi').val() // send currently selected province
},
success: function(response) {
// build the new <select> and append it
var html = $('<p>Sekolah: <select>' + response + '</select></p>');
$('body').append(html);
}
});
I have integrated into a third party delivery service which I populate via Jquery.
[town] -> dropdown
[suburb] -> dropdown
On page load all the select elements are blank. When the user selects town, it then populates suburb.
Now in the event of a post to the server and a returned error, I want to set the form to the state the form was posted in by adding a select element to the correct drop down values.
As an example, user selects town_id 5 and suburb_id 105, form is posted, and returned due to an error. At this point I wish to populate town with value 5 and suburb with value 105...
HTML code:
<div class="form-group col-md-6">
Your town<span class="require">*</span>
<select name="town_id" id="mds_towns">
<option value="">Select your town</option>
<option value="2">Town1</option>
<option value="3">Town2</option>
<option value="4">Town3</option>
</select>...
<div class="form-group col-md-6">
Your town<span class="require">*</span>
<select name="suburb_id" id="mds_towns">
<option value="">Select your suburb</option>
<option value="2">Suburb1</option>
<option value="3">Suburb2</option>
<option value="4">Suburb3</option>
</select>...
I am no jquery expert and I am struggling with the concept of how to get the correct values on a return post.
One of my ideas was to have a special span element with each form field, so something like:
<span id="suburb_value" value="105"> <-----------------*** ADD THIS ***
<div class="form-group col-md-6">
Your town<span class="require">*</span>
<select name="suburb_id" id="mds_towns">
<option value="">Select your suburb</option>
<option value="2">Suburb1</option>
<option value="3">Suburb2</option>
<option value="4">Suburb3</option>
</select>...
Now when the page loads, I populate the span field via php
<span id="suburb_value" value="<?=$suburb_id;?>">
Next the javascript does an ajax call to the api and returns with the list of towns. I then check the value in the span fields and if a value is found, I add a select element to the associated select value...
Would this be on the right path?
Try this:
<script>
$(document).ready(function() {
var townId = <?= (isset($_POST['town_id'])) ? (int) $_POST['town_id'] : 0; ?>,
suburbId = <?= (isset($_POST['suburb_id'])) ? (int) $_POST['suburb_id'] : 0; ?>;
if (townId > 0 || suburbId > 0) {
// make your api call here with townId and suburbId
}
});
</script>
If I understand you correctly, you simply want to retain the selected values in the dropdowns after the page is reloaded on submit. In this case, using jQuery you could try something like:
<script>
$(function(){
var town_id, suburb_id = false;
// Here we assign values to these JS variables if they come through via PHP's $_REQUEST.
<?php echo (!empty($_REQUEST['town_id']) ? 'town_id = '.intval($_REQUEST['town_id']).';' : '') ?>
<?php echo (!empty($_REQUEST['suburb_id']) ? 'suburb_id = '.intval($_REQUEST['suburb_id']).';' : '') ?>
// Here we make the correspondings dropdown options selected, if needed.
if (town_id !== false) {
$('select[name=town_id] option[value='+ town_id +']').attr('selected', 1);
}
if (suburb_id !== false) {
$('select[name=suburb_id] option[value='+ suburb_id +']').attr('selected', 1);
}
});
</script>
More elegant way of doing this would be to pre-select the OPTIONs while outputting the page via PHP, but it's hard to suggest anything in this regard not knowing the structure of your application.
I have a populated MySql database, my database has two columns (item_ID, item_title), and my HTML page has a select box, where all the item_IDs are stored, and below it I have a input box, now I want to do the following:
When the user selects an item_ID from the select box, it should go to the database and find out what is the item_title that belongs to that item_ID.
I am currently using PHP, I don't know how to carry such task.
Thank you in advance.
NB: I am okay populating the select box with all the available item_IDs. The only thing I am not sure how to implement is to retrieve the item_title dynamically as the item_ID changes, and display inside input box.
<select name='item_ID'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<input name='item_title' value='Should change as the item_ID changes' />
Let's say you generate your select element dinamically with PHP:
<?php
while($row = mysql_fetch_assoc($some_query)) {
echo "<option>" + $row["id"] + "</option>";
}
?>
Right? But now why not add the title in the same query and generate the select with it?
echo "<option data-title='" + $row["title"] + "'>" + $row["id"] + "</option>";
Nice, so your select will looks like:
<select name='item_ID'>
<option data-title="Title 1">1</option>
<option data-title="Title 2">2</option>
<option data-title="Title 3">3</option>
<option data-title="Title 4">4</option>
</select>
Now you bind a change event to the select like this:
$("#item_ID").on("change", function(e) {
var selectedOption = $("option:selected", this);
$("#item_title").val($(selectedOption).data("title"));
});
Don't forget to add id="item_title" to your title field.
So, with this approach you won't need an extra request and extra query to database in order to get the title by adding it in the same query that you use to create the select(with inner/left join if its from another table, I think). Thus, it will increase your application performance.
UPDATE:
The event binding should stay on the ready event of the document, like this:
$(document).ready(function() {
$("#item_ID").on("change", function(e) {
var selectedOption = $("option:selected", this);
$("#item_title").val($(selectedOption).data("title"));
});
});
And for more columns you just add them with data- prefix to the option element attributes:
<option data-title="" data-other-property=""></option>
And so on... Then to access it you use the same method:
$(selectedOption).data("title");
$(selectedOption).data("other-property");
Considering selectedOption stands for the option element.
Some references the worth a reading:
Using data attributes # MDN
$(document).ready() # jQuery Learning Center