How to add "required" in WooCommerce variation select option - javascript

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.

Related

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

grab php output using javascript in table

I have an HTML table that is generated from php. I utilize javascript to do something when someone selects a particular answer in a dropdown. The part of the table I care about is here:
<td style="display:none;">
<?= $lineID ?>
<value="<?= $lineID ?>"></td>
<td>
<?= $resolution ?><br>
<value="<?= $resolution ?>">
<select name="resolution[]" class="inputbox" onchange="submitResolution(this.value)">
<option value="null">
</option>
<option value="nightmareAlias.php">ADD NEW ALIAS</option>
<option value="NO PROBLEM">NO PROBLEM</option>
</td>
and here's the script that is actioned when someone selects "ADD NEW ALIAS"
<script>
function submitResolution(str) {
console.log(str);
if (str =="nightmareAlias.php") {
document.getElementById("txtHint").innerHTML="";
$("#txtHint").load(str);
return;
}
}
</script>
Right now - this works just fine. When someone selects ADD NEW ALIAS, they are redirected to the nightmareAlias.php page. When that page loads, I need to find a way to not just submit(this.value), but to almost submit the lineID of the line on the table that the person is actioning.
How do I pass this value along as well?
<select name="resolution[]" class="inputbox" data-lineid="<?= $lineID ?>" onchange="submitResolution(this)">
<option value=""></option>
<option value="nightmareAlias.php">ADD NEW ALIAS</option>
<option value="NO PROBLEM">NO PROBLEM</option>
</select>
You need to make the line ID available, I've included it as an attribute in the select tag. Then pass this as a parameter rather than this.value so that you can access the object in its entirety.
<script>
function submitResolution(sel) {
console.log(sel);
if (sel.value === "nightmareAlias.php") {
document.getElementById("txtHint").innerHTML="";
$("#txtHint").load(sel.value + '?lineID=' + $(sel).data('lineid'));
return;
}
}
</script>
Then add a query parameter to the URL. You will need to handle a GET request for lineID within nightmareAlias.php.
Note the use of === rather than ==, it would also be worth separating your JavaScript and HTML more. For what you're trying to do here I would have probably used .change()

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

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';
}
?>

Remove value from option select

Have any chance to remove exp. value="1" option select?
Exp. that is my option select:
<select name="animals">
<option value="0">dog</option>
<option value="1">cat</option>
</select>
How to remove value="0" and value="1"?
I try this, that is my form:
<form method="post" action="/user/register/" onsubmit="test(this)">
<select name="animals" id="animals">
<option value="0">dog</option>
<option value="1">cat</option>
</select>
</form>
That is my test function:
function test(form) {
form["#animals"].removeAttr("value");
}
But have error message:
form['#animals'] is undefined
Using jQuery:
$('option').removeAttr("value");
Remove an option :
$("select option[value='0'], select option[value='1']").remove();
Try:
$('select[name="animals"] option[value="1"]').remove();
Two problems exist with your function
form["#animals"] is not the correct way to retrieve a element from a form.
Use form["animals"] - use the name directly with no css selector
form["animals"] is not a jQuery object so the removeAttr will fail.
Use $(form["animals"])
Instead just use $(form["animals"]).find('option').removeAttr('value')
Update:
//this will remove the attributes at load time
$(function() {
$('#animals option').find('option').removeAttr('value');
});

Categories