How keep the selected value for dropdown after submit using javascript - 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';
}
?>

Related

How to add "required" in WooCommerce variation select option

I am trying to make woocommerce product variation field required I put the bellow script before </head> but is not working.
How Can I do this?
It works on Jsfiddle but not in my site what I am doing wrong.
My HTML:
<select id="color" class="" name="attribute_color" data-attribute_name="attribute_color">
<option value="" selected="selected">Choose an option</option>
<option value="White" class="attached enabled">White</option>
<option value="Black" class="attached enabled">Black</option>
</select>
My Script:
$(document).ready(function() {
$('select').prop("required", true);
});
Thanks.
On WordPress you need to use first jQuery, then adding $ to function($). This way you can use shorthand $ afterwards.
Here is your code:
jQuery(document).ready(function($) {
$('select#color').prop("required", true);
});
(I have add the id color to select html tag in the jQuery selector. You can either remove it like in your code)
For the record, if it is not required to do in jQuery but rather on backend side, which was my case and is also most efficient. I highly recommend using the woocommerce_dropdown_variation_attribute_options_html filter like so:
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', [ 'make_size_attr_required' ], 10, 2 );
function make_size_attr_required( $html, $args ) {
if ( 'pa_taille' === $args['attribute'] ) {
$html = str_replace( '<select id="pa_taille"', '<select required id="pa_taille"', $html );
}
return $html;
}
This will only add the "required" HTML attribute into the wanted select, which here is "pa_taille", the product variation name you want to happen to.

Select2 - Multiple tags not working

I'm trying to use Select2 (https://select2.github.io) to allow a user to type multiple tags into a field before submitting a form. In my Laravel PHP app, I'll then take those tags, determine if they exist and add them into a database.
My problem is that I can't seem to get Select2 to recognise there are multiple tags being entered by the user. When I interrogate the form data, I only see the LAST tag a user typed as opposed to ALL the tags.
My Select2 element is:
<select class="tags-field" name="tags" data-tags="true" data-placeholder="TAGS" multiple="multiple">
</select>
and my JQuery is:
$(function() {
$(".tags-field").select2({
maximumSelectionLength: 3,
tokenSeparators: [','],
});
}
There are no Javascript errors and it works perfectly fine except I cannot detect ALL the tags.
To cause PHP to make all the selected choices available as an array, suffix your select name with a pair of square brackets, like this:
<select class="tags-field" name="tags[]" data-tags="true" data-placeholder="TAGS" multiple="multiple">
If this form is sent to a PHP program, the value of $_POST['tags'] will be an array. Note that the square brackets in the form control name aren't a part of the array key. You would process such a form like this:
<?php
$tags = $_POST['tags'];
// Note that $tags will be an array.
foreach ($tags as $t) {
echo "$t<br />";
}
?>
References here: http://bbrown.kennesaw.edu/papers/php2.html
use hidden input field in order to send all values
use onsubmit event to set the value of the hidden field
HTML:
<form method="post" action="post.php">
<select multiple id="e1" style="width:300px" name="_state">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<input type="hidden" name="state" value="" />
<input type="submit"/>
</form>
JQ:
$("#e1").select2();
$('form').submit(function () {
var newvalue = '';
var value = $('select[name="_state"]').val();
if (value) {
newvalue = value;
}
$('input[name="state"]').val(newvalue);
})

Writing Conditional Drop Downs to MySQL

Hopefully this isn't too confusing..
I have a conditional form that has the user select a category, based on that category they'll need to choose from that category's sub categories. This works fine.
However, my issue is when writing to MySQL the Value that's inserted in my Sub Category column is always the last Select group's first Value (in this case it's "sandwich"). Example..
My Main Categories: Starters | Supper | Sandwiches
Starters' Sub Categories: Coastal or Southern
Supper's Sub Categories: Smokehouse or Specialties
Sanwiches' Sub Categories: Sandwich or Po-Boy
No matter which Category/Sub Category you select, it always writes the "Sandwich" subcategory in MySQL. Make sense?
So here's my code & JSFiddle if you want to play with the dropdowns. http://jsfiddle.net/kkobayashi/5f5tw4t0/
PHP to MySQL
<?php
if( isset( $_POST['create'] ) ):
$cat = $_POST['cat'];
$catsubs = $_POST['subcategory'];
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
mysql_query("INSERT INTO leDB (cat,subcategory)
VALUES('$cat','$catsubs')")
or die(mysql_error());
echo "Success."; /** success message **/
endif;
?>
HTML
<form action="" method="POST">
<!-- MAIN CATS -->
<select id="mainCat" class="source" name="cat">
<option value="starters">Starters</option>
<option value="supper">Supper</option>
<option value="sandwiches">Sandwiches</option>
</select>
<!-- SUB CATS -->
<div id="cat_starters" class="subcategory" style="display:inline;">
<select class="" id="starters" name="subcategory">
<option value="coastal">Coastal</option>
<option value="southern">Southern</option>
</select>
</div>
<div id="cat_supper" class="subcategory hidden">
<select class="" id="supper" name="subcategory">
<option value="smokehouse">Smokehouse</option>
<option value="specialties">Specialties</option>
</select>
</div>
<div id="cat_sandwiches" class="subcategory hidden">
<select class="" id="sandwiches" name="subcategory">
<option value="sandwich">Sandwich</option>
<option value="poboy">Po-Boys</option>
</select>
</div>
</form>
JS
// Conditional Drop Down
$(document).ready(function(){
$('#mainCat').on('change', function() {
// Setting this variable to add inline
var inline = document.querySelector('#cat_' + $(this).val() );
// Show/Hide
$('div.subcategory').hide();
$('#cat_' + $(this).val() ).show();
inline.style.display = "inline";
});
});
A little CSS
div.hidden {
display: none;
}
Don't know how well of a job I did describing the issue, if you're confused feel free to yell at me. Thanks y'all.
Hiding the select does not actually remove it from the DOM, as you would see if you would check the source. It only hides it from the user.
This means that every select with the same name attribute will override the last one, hence why you only get the last one.
an easy fix could be to add the name attribute to the correct select.
$(document).ready(function(){
$('#mainCat').on('change', function() {
// Setting this variable to add inline
var inline = document.querySelector('#cat_' + $(this).val() );
// Show/Hide
$('div.subcategory').hide().attr('name', '');
$('#cat_' + $(this).val() ).show().attr('name', 'subcategory');
inline.style.display = "inline";
});
});
you need to add unique names to your selects.
For example for starters, add name="starters". Add names as the option values of the category.
And after that, use: $catsubs = $_POST[$cat];
Change the subcategory names to maybe subcategory1, ...2 and ....3 or just make them unique in the form
You need the names to be unique. The reason you end up with the same sandwich no matter what you select is because you are using the same name. When the $_POST data is sent, it sends an array with the key equal to the name in the form. So to know exactly what a user clicked, selected or typed, each name must be unique

Add/Removing Options with JQuery

I'd like to add and remove options from one drop down menu using JQuery given a selected option in another.
HTML:
<form action='quickLook.py' method = 'post'>
First DropDown Menu
Specify Channel:
<select id='bolometer'>
<option selected id='Dual' value = 'Dual' >Dual
<option id='Top' value = 'Top' >Top
<option id='Bottom' value = 'Bottom' >Bottom
</select>
Second DropDown Menu
<br>Specify Data to Display:
<select id='target'>
<option selected id='Spectrum' value = 'Spectrum'>Spectrum
<option id='Interferogram' value = 'Interferogram'>Interferogram
<option id='SNR' value = 'SNR'>SNR
<option id='Diff_Band' value = 'Diff_Band'> Diff_Band
</select>
<input type='submit' value= 'Query Images'>
</form>
I'd like to do something like this is JQuery:
$("#Dual").click(function() {
$("#target").append("#Diff_Band");
$("#target").remove("#Interferogram");
$("#target").remove("#SNR");
});
$("#Top").click(function() {
$("#target").append("#Interferogram");
$("#target").append("#SNR");
$("#Diff_Band").remove();
});
I want to append or remove the already written html.
What is the best way to do this?
Thank you for your time!
This is a similar problem I've encountered before working with Safari. A solution is to use .detach() instead of remove() as it keeps all jQuery data associated with the removed elements. Check this jsfiddle: http://jsfiddle.net/Ueu62/

jQuery input not hidden

I'm working on a new website based on CodeIgniter. I'm trying to hide some elements to my form depending on an input value, but the field doesn't hide but stays disabled.
Here's the code I have :
HTML :
<div class="clearfix">
<label for="form-timezone" class="form-label">Filters<small>Options</small></label>
<div class="form-input">
<?php
echo form_dropdown('filter', $filters,'', 'id="form-timezone"');
echo form_dropdown('city', $cities, '', 'id="city"');
echo form_dropdown('country', $countries, '', 'id="country"');
?>
</div>
</div>
Which basically gives something like :
<div class="clearfix">
<div class="form-input">
<select name="filter" id="form-timezone">
<option value="city">City</option>
<option value="country">Country</option>
</select>
<select name="cities" id="city">
<option value="Paris">Paris</option>
<option value="London">London</option>
</select>
<select name="countries" id="country">
<option value="fr">France</option>
<option value="en">England</option>
</select>
</div>
</div>
JS :
$(function() {
$("#city").hide();
$("#country").hide();
$("#form-timezone").change(function() {
if ( $("#form-timezone").val() == "city"){
$("#city").show();
$("#country").hide();
}
else if ( $("#form-timezone").val() == "country"){
$("#city").hide();
$("#country").show();
}
});
});
I tried to add an <input> field to my html, and to hide it in the js, and it worked well. I don't know why, but it seems that only the form_dropdown doesn't hide...
Do someone has an idea of what I'm doing wrong please ?
Thanks.
I don't know what you mean by not working. But your code can be a lot simpler with no if statements.
$("#form-timezone").change(function() {
var el = $('#' + $(this).val()); // <-- store matched element
el.show(); // <-- show matched element
$("#country,#city").not(el).hide(); // <-- hide unmatched element
});
And they work fine in this fiddle (they hide and not disable) - tested in Firefox/Chrome/IE9
http://jsfiddle.net/5LNWr/1/
It works for me in this fiddle.
The Javascript code you posted was missing a closing }); after the DOM ready handler. I've assumed the output is a <select> element for each PHP echo statement.
You mention that the form field "stays disabled." Does this mean they're disabled to begin with? Disabled form elements don't capture events in all browsers (Firefox).
If that isn't the case, can you provide a jsfiddle?
<div class="clearfix">
<div class="form-input">
<select name="filter" id="form-timezone">
<option value="city">City</option>
<option value="country">Country</option>
</select>
<!-- Here a select foreach city and country -->
</div>
</div>
See how there is no id's for City and Country? You cannot select on ID's here.
$("#city").show();
$("#country").hide();
Won't work. Maybe try
var $firstOption= $(“#form-timezone option:first”)

Categories