html multiple select chosen js submit form - php

I have this easy select in PHP as echo (using Chosen JS):
echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\"
data-placeholder=\"Country...\" multiple class=\"chosen-select\">
<option value=\"dontcare\">dontcare</option>";
foreach ($states as $state) {
echo "<option value=\"" . $state->stat .
"\" >" . $state->stat . "</option>";
}
echo "</select> </th></tr>";
after submitting from and refreshing page values are not as selected.
If i have select with only one choice this is working for me:
var my_val = '<?=$_POST['price']?>';
$("#cenan").val(my_val).trigger("chosen:updated");
but i dont know how to set it as selected in case of array. Can you help me and show me some code? I spent hours and hours without any result.

You are POSTing the form data to the same page and then refreshing it, right?
If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array.
Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. Much easier on the eye.
foreach ($states as $state) {
if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
echo "<option value='$state->stat' selected>$state->stat</option>";
} else {
echo "<option value='$state->stat'>$state->stat</option>";
}
}

Lets suppose you have HTML select like following :
<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
Here is the solution :
<?php
$arr = ['a','b']; // PHP Sample Array
?>
var js_json = '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']
// initialize
$("#firstselect").chosen();
// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});
//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");

Related

How to get the complete value of an option tag?

I have this code using php
<select id="sem" name="y[]">
<option>Year</option>
<?php
$petsa = new DateTime();
$yr=$petsa->format('Y');
$a=$yr+1;//2015
$b=$yr-1;//2013
for($y=$b;$y<=$a;$y++)
{
$bb = $y+1;
echo '<option value="'.$y.'"'.'-'.$bb;
if(isset($_POST['y'])){
if (in_array($y."-".$bb,$_POST['y'])){
echo 'selected="selected"';
}
echo '/>'.$y."-".$bb;
}else
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
echo "</option>";
}
?>
</select>
if(isset($_POST['submit'])){
$sem= $_POST['sem'];//this is from other field
foreach ($_POST['y'] as $yer);
$osql2 = "INSERT INTO sy VALUES('$sem','$ss')";
if (mysql_query($osql2)){
echo "Successfully Added!";
}
This code work well almost but the problem is when i call the value of the option tag it just give me this value $ss=2014 and it should be like this $ss=2014-2015
what is wrong with my code? that code generate SY from 2013-2014 to 2015-2016
please help me.
Look at the generated HTML. Look at where the quotes around the attribute value are. They are currently very wrong.
Stop trying to generate HTML by mashing together lots of different strings. It becomes very hard to see what is going on.
$value = $y . "-" . $bb;
?>
<option value="<?php echo htmlspecialchars($value); ?>">
<?php echo htmlspecialchars($value); ?>
</option>
<?php
I suspect it's your use of quotes here:
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
I would change it to this:
echo "<option value ='$y"."-"."$bb"."'>".$y."-".$bb;
I have moved the second ' to just before the > of the opening option tag.
The single quote ' was for the option tag, and the double quote " was for the PHP string, you were simply cutting the value for option short

HTML dynamic number of elements in a form with post

I have code that basically uploads a spreadsheet of data, could have 5 columns or 10 columns or whatever. Each column needs to have a drop down box specifying the data type, and the data types selected should be submitted via post with a form to another php site. How would I do this, this is the code that creates the elements.Is there a way to dynamically create elements, like delimist . attCount, and how would i put this loop into an html form to submit the data? Is there any way to put the values of all of these into an array for convince? Thanks.
EDIT: Ok thanks for the dynamic stuff, but how would i put this into a form and submit this via post to another page. Or is there another way to post information. I dont know much about php.
while($attCount < count($attArray)) {
echo "<select name=\"delimList\">";
echo "<option value=1>tab</option>";
echo "<option value=2>comma</option>";
echo "<option value=3>semi-colon</option>";
echo "<option value=4>ampersand</option>";
echo "<option value=5>pipe</option>";
echo "</select>";
$attCount = $attCount + 1;
}
Using a foreach loop and assigning the first index in your array will give you what you're expecting:
$options = [1=>'tab','comma','semi-colon','amperstand','pipe','another-value'];
echo "<select name=\"delimList[]\">\r\n";
foreach($options as $val => $option){
echo "<option value=\"$val\">$option</option>\r\n";
}
echo "</select>\r\n";
output:
<select name="delimList[]">
<option value="1">tab</option>
<option value="2">comma</option>
<option value="3">semi-colon</option>
<option value="4">amperstand</option>
<option value="5">pipe</option>
<option value="6">another-value</option>
</select>
To sumbit the page you'll need to put everything inside of
<form method="post"> // you may want to add an action="..."
.... // if you want to post to another page,
</form> // instead of the same one
You'll also need a submit button too...
<input type="submit" name="submit" value="submit" />
After submit you can check the values like this:
if(isset($_POST['delimList'])){
foreach($_POST['delimList'] as $key => $value){
echo "delimList[$key] = $value";
}
}
You can put all the value of all of these into an array… by putting all the values of these into an array!
$myArray = ['tab','comma','semi-colon','amperstand','pipe','another-value'];
echo '<select name="delimList">';
for ($i = 0; $i < count($myArray); $i++) {//Loop thru all
echo '<option value="'.$i.'">'.$myArray[$i].'</option>';
}
echo "</select>";

Retaining dropdown selection on postback creates empty options

I want to retain the users dropdown selection after the form has been submitted, however, since I added the code to do this it has created empty options in my dropdown list (even before anything is submitted). What is happening and how can I rectify it? Any help is very much appreciated.
$sals = array('Mr','Mrs','Miss','Dr');
<label>Salutation: </label>
<select name='mysal'>
<?php
foreach ($sals as $sal) {
echo "<option value='$sal'";
if($sal == #$sal_conf) echo 'SELECTED';
echo ">".$sal."<option />";
}
?>
If submit button (omitted here) is pressed:
if (isset($_POST['submit']))
{
$sal_conf = $_POST['mysal'];
}
Opening the drop down list look like this
Mr
Mrs
Miss
Dr
There is an empty selection after each option.
Give it a try.
<?php
foreach ($sals as $sal) {
$selected = ($sal == $sal_conf) ? ' SELECTED' : '';
echo '<option value="'.$sal.'"'.$selected.'>'.$sal.'</option>';
}
?>
You have not closed your
<option></option>
i find it cleaner to use curly braces {} when I have inline variables instead of closing the string when am using double quotes.
foreach($sals as $sal){
echo "<option value={$sal}";
if($sal == #$sal_conf) {echo "SELECTED "; }
echo " >{$sal}<option />";
}

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

How can I add text into a certain area?

If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?

Categories