JQuery cloning of select areas and passing all to PHP Array - javascript

I need to pass cloned areas of a form to PHP via post an add then each to an array.
My code
<div class="input-main white_bg cloneneedsanalysis">
<div class="action-input clone-needs-analysis">
<div class="action-input-white-shorter">
<div class="inner-sub-title-less-padding">
<p>Audience Analysis</p>
</div>
<div class="col-md-12">
<div class="form-group">
<select class="select2 select2-multiple" multiple="multiple" data-placeholder="Choose ..." name="needs_analysis[]">
<option value="">-- Choose Audience Categories --</option>
<option value="536"> Finance - - Cash collection </option>
<option value="537"> IT - - Comms IT </option>
<option value="538"> Strategy - - Strategy team 1 </option>
</select>
</div>
</div>
</div>
<div class="action-input-plus-needs-analysis"> </div>
<div class="action-input-remove-needs-analysis"> </div>
</div>
</div>
The cloning works, but when I send to PHP via POST it will only capture the last one because they are all called called needs_analysis[]
So, when cloning how can I edit the name so that it's different and how can I get PHP to loop though each of the arrays?
My JQuery;
$(document).on('click', '.clone_needs_analysis_button', function(e) {
e.preventDefault();
$(this).closest('.clone-needs-analysis').clone().insertAfter('.cloneneedsanalysis:last');
$(this).closest('.action-input-plus').hide();
$(this).closest('.action-input-remove').removeClass('hidden');
My PHP;
$needs_analysis = array();
foreach ($_POST['needs_analysis'] as $key => $value) {
$needs_analysis[$key]['audience_id'] = $value;
$needs_analysis[$key]['created'] = $_POST['updated'];
$needs_analysis[$key]['created_by'] = $_POST['updated_by'];
$needs_analysis[$key]['solution_id'] = $_POST['solution_id'];
}
foreach ($needs_analysis as $needs_analysis_insert) {
$db->insert('design_needs_analysis', $needs_analysis_insert);
}

Your names for the multi-select should look like this:
needs_analysis[1][]
needs_analysis[2][]
You can either do this server-side, when generating the page, or rename them in JavaScript:
$('[name="needs_analysis[]"]').each(function(index) {
var currentElement = $(this)
currentElement.attr('name', 'needs_analysis['+index+'][]')
})
In order to loop through the values in PHP, you could do this:
foreach ($_POST['needs_analysis'] as $k=>$v) {
//$v represents the value array for a select element
foreach ($v as $k2=>$v2) {
//do something with each value
}
}

Related

Change content based on a drop down selection from a mysql database

I have a form of drop down boxes populated with values from a mysql database (Computer Part Models). My goal is to produce the rest of the values (The part's specs) from the database below each drop down box based on the value that was selected.
Essentially what I think I think I need is some sort of div refresh for each time a new item has been selected.
I have tried different functions triggered by 'onchange' within the select tag but nothing has come up working.
Let me know if anymore code would be needed for context.
HTML & PHP for one drop down
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<?php
$cresult = $mysqli->query("SELECT * FROM pCpu ORDER BY cModel asc");
?>
<select id="CPU" name="CPU">
<option value="" disabled selected>Select your Part</option>
<?php
while ($rows = $cresult->fetch_assoc()) {
$cmodel = $rows['cModel'];
echo "<option value='$cmodel'>$cmodel</option>";
$cid = $rows['ID'];
}
?>
</select>
<br/>
<?php
$res = $mysqli->query("SELECT cSocket FROM pCpu WHERE ID = '$cid'");
while($rows = $res->fetch_assoc()) {
$csocket = $rows['cSocket'];
echo "CPU Socket: $csocket<br/>";
}
?>
<br/><br/>
What would be the best way of tackling this?
Thanks in advance!
There's two parts in this answer :
First if you want to update a part of your page with change event on the select
function myUpdateFunc()
{
var mySelected = $("#CPU").find("option:selected").val();
$('#divResults').html ('selected value :' + mySelected)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<select id="CPU" name="CPU" onchange="myUpdateFunc()">
<option value="" disabled selected>Select your Part</option>
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
<br/>
<div id="divResults"/>
<br/><br/>
Next :
If you want to query a database you can check many tutorials on this. I can help you with this as well

Using the filters i choose i want to filter my json array so that only those rows will be displayed

so far this is what i have done
<div class="dropdown">
<p class="filter-text">LANGUAGE</p>
<select class="selection" name="language" multiple id="lang">
<option value="CH">Chinese</option>
<option value="EN">English</option>
<option value="JP">Japanese</option>
</select>
</div>
js:
`$("#language :selected").map(function ( i, el ) {
var values = $(el).val();
console.log(values);
// customfilter(values);
});
function custonfilter(){
....//HELP//
}`
My json is coming from an ajax request and looks like:
var json=[{marketName: "Asia",language:english},
{marketName: "Asia",language:chinese},{marketName: "Asia",language:japanese},
…}]
So, when user checks on english my new json shud contain all rows with language=english.

Put value from javascript combo box

I want to get the value from a combo box in javascript.
This is the combo box code:
<select name="no_kk" style="width: 68%;" class="select2" id="no_kk" onchange="get_Nokk(this.value);" >
<option value="">-- Pilih Nomor KK --</option>
<?php
$kk = get_no_kk();
foreach ($kk as $key => $value) {?>
<option value="<?php echo $value->no_kk;?>"><?php echo $value->no_kk;?></option>
<?php
}
?>
</option>
</select>
I want to put the value I choose in this code here:
<div class="right">
TAMBAH
</div>
Here you have a problem. Is better for you to leave the href empty and then replace it using JS. I let you an example:
function calculateURL(option){
return a + option;
}
(function() {
console.log(document.querySelector(".button-submit-blue").href)
document.querySelector("#mySelect").addEventListener("change", function(evt){
var option = document.querySelector("#mySelect").value;
document.querySelector(".button-submit-blue").href = calculateURL(option);
alert("The value selected is: "+document.querySelector("#mySelect").value);
alert("The new link is: " + document.querySelector(".button-submit-blue").href)
}, false);
})();
<script>
var a = "http://www."; //this represents values grab from PHP
</script>
<select id="mySelect">
<option value="">--</option>
<option value="google.com">google</option>
<option value="yahoo.com">yahoo</option>
</select>
<div class="right">
TAMBAH
</div>
This is easy. First of all you need to set a listener for the change event on your select. This is set using addEventListener function. This function has several arguments, the first is the event you want to listen, change, the second is the callback, which will be executed everytime the event change is fired. Finally, you only have to take the selected option and recalculate your url.

How keep the selected value for dropdown after submit using javascript

How do I keep the selected item after page refreshed ,i have a language in the multiple select,
i am try now this with java script here is my code its not working ,can any one guide me how to make it selected
my html code
<div class="control-group">
<label for="textfield" class="control-label">Language</label>
<div class="controls">
<select name="myLanguage" id="myLanguage" multiple="multiple">
<option value="English,">English,</option>
<option value="Arabic,">Arabic,</option>
<option value="Hindi,">Hindi,</option>
<option value="Malayalam,">Malayalam,</option>
<option value="Danish,">Danish,</option>
</select>
</div>
</div>
javascript
document.getElementById('myLanguage').value = "<?php echo $_GET['language'];?>";
If you use jQuery use this:
$(document).ready(function(){
$('#myLanguage').val("<?php echo $_GET['language'];?>");
});
Javascript doesn't use a session variables, so adding the value to the session isnt possible. Still you can do two things:
Option 1:
Add the value to a cookie with Jquery:
Set: $.cookie("test", 1);
Read: var value = $.cookie("test");
See more: How do I set/unset cookie with jQuery?
Option 2:
Post the value to the new page and request on that one:
Reading the value can be done with :
Read: $_REQUEST["my_variable"];
Note: reading value can be done like:
$("#myLanguage option:selected").text();
If you're using HTML5 as your doctype you can easily store values in the localStorage.
Reference: http://www.w3schools.com/html/html5_webstorage.asp
To set it:
localStorage.setItem("variable_name", variable_value);
To get it:
localStorage.variable_name
To remove it:
localStorage.removeItem("variable_name");
You can also use js cookies with jquery.cookie plugin, if you prefer.
As mentioned in the comments, when using the multiple attribute,
the name attribute must be an array such as:
<div class="control-group">
<label for="myLanguage[]" class="control-label">Language</label>
<div class="controls">
<select name="myLanguage[]" multiple="multiple">
<option value="English,">English,</option>
<option value="Arabic,">Arabic,</option>
<option value="Hindi,">Hindi,</option>
<option value="Malayalam,">Malayalam,</option>
<option value="Danish,">Danish,</option>
</select>
</div>
</div>
javascript // Note: I'm not so sure on the following syntax
var myLanguage[] = document.elements('myLanguage[]').value;
<?php
$languages = array(
'en' => 'english',
'vi' => 'vietnamese',
'cn' => 'chinese'
);
if (isset($_GET['lang']) AND array_key_exists($_GET['lang'], $languages))
{
include './lang/' . $languages[$_GET['lang']] . '.php';
}
else
{
include './lang/english.php';
}
?>

<select> tag returns an empty value to the database

So I am trying to create a dropdown that loops through $countries and then the selected country is written to $country in the database under the user table. I got the dropdown, but it returns a null value to the database (well the validation at least).
Here is the call for the dropdown
<div class="form-group col-lg-6 col-sm-12">
<label for="country">Country</label>
<div id="countrydd">
#if(isset($currentCountry->name))
<select name="country" id="country_display" class="current-value-da-select closed">
{{(isset($user->country->name))?$user->country->name:$currentCountry->name}}
#foreach($countries as $country)
<option value="{{$country->name}}">{{$country->name}}</option>
#endforeach
</select>
#else
<select name="country" id="country_display" class="current-value-da-select closed">
{{(isset($user->country->name))?$user->country->name:'Select your Country'}}
#foreach($countries as $country)
<option value="{{$country->name}}">{{$country->name}}</option>
#endforeach
</select>
#endif
And this is the Javascript for the dropdown
//Country Drop Down
$('#countrydd').click(function(e) {
var selectWrapperCountry = $('#countrydd');
var currentValueCountry = $(this).find('a').html();
selectWrapperCountry.find('.current-value-da-select').html(currentValueCountry);
selectWrapperCountry.find('#country').val(currentValueCountry);
updateCarretClassCountry();
});
$('#countrydd a.current-value-da-select').click(function() {
updateCarretClassCountry();
});
function updateCarretClassCountry(){
if($('#countrydd a.current-value-da-select').hasClass('closed')) {
$('#countrydd a.current-value-da-select').attr('class', 'current-value-da-select opened');
}
else
{
$('#countrydd a.current-value-da-select').attr('class', 'current-value-da-select closed');
}
};
Any help to get the value to update right would be awesome.
It seems that you are using the select tag wrong. Select needs to have a name (that is what you will get as a post variable), and every option needs to have a value. So it would be something like this:
<select name="country">
<option value="1">First one</option>
<option value="2">Second one</option>
</select>
After the form is submitted, you would have
echo $_POST["country"]; //This will output 1 if First one is selected and 2 if Second one is
Also, why do you have <a> inside <option> ?
Read more at: http://www.w3.org/wiki/HTML/Elements/select

Categories