How to make dimanic input select option in chained dropdown option? - javascript

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);
}
});

Related

How to use the value of an input to render specific content on the same page without a page refresh or a form submit in Laravel 8

I am trying to build a student catalog. I have a structure which consists in Classes -> Groups -> Students.
I already have the classes and groups in my database. Each group belongs to a class.
As an example, I go to my Class page and I create class 1. After this, I go to my group page and add a group "A" that has class 1 assigned to it. I can add multiple groups to each class.
Now I want to create a student on my student page. To do this, I want to add the student in a specific group. To be able to chose the group, the admin has to firstly select the class from a select dropdown. After the class gets selected, the next select will render only the groups assigned to the selected class.
My solution for this right now is to set the $_GET super global with the class id that was selected by the user in the first dropdown. I do this via javascript function with window.location.href url change. I set the logic of the group dropdown to look for the $_GET variable before it renders the options.
I don't think this is a clean and good approach as the page is always refreshed when the location is reset and the input values are always reset.
I just want to use whatever the user has selected from the classes dropdown to render the options in the group dropdown. Is there anything that Laravel 8 built in features can do for me regarding this issue?
As a sample of what I am doing right now:
<select name="classes" id="classes" onchange="getClassID()"> // getClassID just changes the location and adds the selected class id to the url as a query string
#php
foreach ($classes as $class) {
if(isset($_GET['classID'])){
if($_GET['classID']*1 === $class->id){
echo " <option value={$class->id} selected>{$class->classes_number}</option>";
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
}
#endphp
</select>
<script>
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let option = document.getElementById("classes").value;
window.location.href='/students/create?classID=' + option;
}
</script>
<select name="group_id" id="group">
#php
// If the user has changed the initial classes select dropdown value, we will
// get all of the groups that have the class that was selected and display them
// as options in this select
if(isset($_GET['classID'])){
$classID = $_GET['classID']*1;
foreach ($groups as $group) {
if ($group->classes_id === $classID) {
echo "<option value={$group->id}>{$group->group_name}</option>";
}
}
}
else {//another code that handles the situation in which all classes are erased}
#endphp
</select>
Images with my form when the user selects different classes and the groups are rendered differently for each selected class:
Instead of reloading the page, you can get the options via api and create the second select on client-side.
var groupIdSelect = document.getElementById('group');
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let classID = document.getElementById("classes").value;
fetch('api/students/create?classID=' + classID)
.then((res) => res.json())
.then((groups) => {
for (group of groups) {
if (group.classes_id === classID) {
var option = document.createElement('option');
option.value = group.id
option.textContent = group.group_name;
groupIdSelect.appendChild(option);
}
}
})
}

Option value doesnt showup in dropdown - jquery

I am trying to add new options in a dropdown based on the other dropdown value.
the new added option doesnt appear in the dropdown on my custom webkit browser.
When I try to debug it the values are present in the dropdown, just it doesnt show up in the front end.
I have attached the code but its working in jsbin :(
When I click the empty dropdown and then click New button value doesnt show up but if I dont click the empty dropdown and click new button directly values appear normally.
https://jsbin.com/kikicuhabo/1/edit?html,css,js,output
It is a good practice to write HTML in lower case, and to close the tags.
If you want to use jQuery I recommend to select elements alway with the "$('')" instead of mixing with the "document. ... "
Since yours it is a custom browser I would try a solution in Vanilla JS.
function AddToCB(p_oCB, p_sText) {
var oSelect = document.querySelector(p_oCB);
var iNewLast = oSelect.length;
var sDisplay = p_sText + (iNewLast + 1);
var oNewItem = document.createElement('option');
oNewItem.innerHTML = sDisplay;
oNewItem.setAttribute('value', sDisplay)
oSelect.appendChild(oNewItem);
oSelect.selectedIndex = iNewLast;
return iNewLast;
}
function AddOption() {
var select = document.querySelector("#cmb");
var text = select.options[select.selectedIndex].value;
AddToCB('#list', text);
}
<select name="cmbColor" id="cmb">
<option>AA</option>
<option>BB</option>
<option>CC</option>
</select>
<input type="button" class="float-right" VALUE="New" onClick="AddOption()" >
<select name="list" id="list">
</select>

How to change value of appended select element in a form

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>

customize java script function from particular page when that method is used by many pages

I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>

giving id to the text field

I have a form at which 2 fields are generated by one drop down menu. Now the problem is I have generated one field and trying to get two fields, in first field price is shown and in second tag product_id is shown. My script is just showing price but not id. Due to lack of knowledge I am stuck. I just need help from someone.
JavaScript:
function setOptions(chosen) {
var selbox = document.myform.opttwo;
selbox.options.length = 0;
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); }
selbox.options[selbox.options.length] = new Option('100 Directory Submission', '$9.99', '1');
selbox.options[selbox.options.length] = new Option('200 Directory Submission', '$19.99', '2');
selbox.options[selbox.options.length] = new Option('300 Directory Submission','$29.99', '3');
}
document.myform.amount.value="";
document.myform.hidden.value="";
}​
HTML:
<select name="opttwo" size="1" onchange="this.form.amount.value=this.value;">
<option value=" " selected="selected">Select any option of the above first</option>
</select>
Amount Payable:<input type="text" readonly="readonly" name="amount" />
Product id:<input type="text" name="hidden" readonly="readonly" />
First off there are some obvious problems with your code such as closed and unclosed braces.
One example of that is on this line:
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); }
Edit: this is not no longer the case.
Secondly, the Options object that you're trying to create does not have the "id" property that you're trying to get unfortunately.
So your code
selbox.options[selbox.options.length] = new Option('100 Directory Submission', '$9.99', '1');
is not getting '1' as its id.
The constructor is
new Option([text], [value], [defaultSelected], [selected])
You can however get the index of an element by doing this in your onchange handler:
this.form.hidden.value=this.selectedIndex;
Thirdly, if you wanna continue on the path of using script in your onchange tags, which generally is discouraged, you have to set the value of the hidden input as well.
Like this:
onchange="this.form.amount.value=this.value; this.form.hidden.value=this.value;"
Note: this line above will give you the wrong value, just saying, but you get the gist of it.
I made a fiddle for you to toy around in and to see how it's done.
Here is it
Some API documentation is always in order I believe:
Update:
In order to set the id dynamically on every Option you have to loop over the elements in the select list like this:
for (var i=0; i<selbox.length; i++){
selbox.options[i].setAttribute('id', 'hello'+i);
}
Then in the line where you set in your onchange() you add this
this.form.hidden.value=this[selectedIndex].id;
Now your input should show, when you select an option, "hello0", "hello1", "hello2", "hello3".
Also, I updated the fiddle for you.
Mozilla Option API

Categories

Resources