How to make Wordpress Woocommerce custom input field required - php

I have written some code to display a select input on the product page, my issue now is that if it is a simple product without variations then the customer can add to the cart without selecting from the input field. Still, I want the input field to be required.
Here's what I have done so far:
add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');
/**
* Adds a custom field for Product
* #return [type] [description]
*/
function wdm_add_custom_fields()
{
global $product;
ob_start();
?>
<div class="wdm-custom-fields>
<label for="fabric">Fabric:</label>
<select id="id_select2_example" name="Fabric" style="width: 150px;">
<option data-img_src="" value="">Choose a Fabric</option>
<option data-img_src="http://localhost/shopneyah/wp-content/uploads/2022/08/19-organic-cotton-satin-fabric-1-250x250-1.webp" value="ash">Ash</option>
<option data-img_src="http://localhost/shopneyah/wp-content/uploads/2022/08/superior-quality-poly-cotton-denim-blue-white-blue-plain-poly-cotton-fabric-close-up-fabric-photo.jpg" value="Light Blue">Light Blue</option>
<option data-img_src="http://localhost/shopneyah/wp-content/uploads/2022/08/poly-cotton-fabric.jpg" value="Dark Blue">Dark Blue</option>
<option data-img_src="http://localhost/shopneyah/wp-content/uploads/2022/08/images-2.jpg" value="light purple">Light Purple</option>
</select>
</div>
<!-- scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
<script type="text/javascript">
function custom_template(obj){
var data = $(obj.element).data();
var text = $(obj.element).text();
if(data && data['img_src']){
img_src = data['img_src'];
template = $("<div><img src=\"" + img_src + "\" style=\"width:35%;height:200px;\"/><p style=\"font-weight: 700;font-size:14pt;text-align:left;\">" + text + "</p></div>");
return template;
}
}
var options = {
'templateSelection': custom_template,
'templateResult': custom_template,
}
$('#id_select2_example').select2(options);
$('.select2-container--default .select2-selection--single').css({'height': '225px'});
</script>
<?php
$content = ob_get_contents();
ob_end_flush();
return $content;
}
add_filter( 'woocommerce_checkout_fields' , 'wdm_add_custom_fields' );
from the image above the fabric input has not been selected but add to cart is clickable, please how do I disable it or stop it from working until a fabric has been selected? Thank you.

Related

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>

Trying to send visitors to another page and open specific div via onChange form event

I have a page called states.php. Each state is hidden until you select it from the dropdown menu. It then shows the state div selected and hides the others. This works perfectly on the states.php page.
However, I have the same form on every other page on the site. I would like to be able to select a state from say, home.php, redirect them to states.php and open the correct states div.
Here's the form and html:
<div class="select"><span class="selectState">Select a State</span><span><form>
<select name="States" id="options" class="form-select">
<option value="state" selected="selected">- Select a State -</option>
<option value="1" >New York</option>
<option value="2" >New Jersey</option>
<option value="3" >Texas</option>
</select>
</form></span></div>
<!-- NY Map -->
<div id="state1" class="state stateShow">
NY CONTENT
</div>
<!-- NJ Map -->
<div id="state2" class="state stateShow">
NJ CONTENT
</div>
<!-- TX Map -->
<div id="state3" class="state stateShow">
TX CONTENT
</div>
And here's the javascript:
$(document).ready(function() {
function optionCheck() {
var i, len, optionVal, stateDiv,
selectOptions = document.getElementById("options");
for (i = 0, len = selectOptions.options.length; i < len; i++) {
optionVal = selectOptions.options[i].value;
stateDiv = document.getElementById("state" + optionVal);
if (!stateDiv) { continue; }
if (selectOptions.options[i].selected) {
stateDiv.className = "state stateShow";
} else {
stateDiv.className = "state";
}
}
}
document.getElementById("options").onchange = optionCheck;
});
And basic CSS:
.state {
display: none;
}
.stateShow {
display:block;
}
Any help would be greatly appreciated.
Thanks
You could put the state value in the hash of your link and then check that in your states.php javascript. For example, on your home page, put the link:
New York
And then in your states.php javascript:
$(document).ready(function() {
function optionCheck() {
// option check logic ...
}
document.getElementById("options").onchange = optionCheck;
if (window.location.hash) {
document.getElementById("options").value = window.location.hash.substring(1);
optionCheck();
}
});

Update Price based on dropdown list selection

I have a dropdown list populated by mysql working perfectly, I also have it displaying the price set by mysql, so far i'm happy.
What the issue is as it's a multiple dropdown list, it will only display what is chosen first, if I pick 2 or more selections, only the first price is shown.
My second issue is I want the prices to add up i.e. 1st Selection's price is £1.99, 2nd Selection's price is £2.99 so the total should be £4.98
Finally once i have all this working, I want to continue this onto the 2nd / 3rd / 4th dropdown boxes so that all the boxes add up giving me a combined total.
Here's my html code to show you what i'm using:
<form method="post" action="" name="form1">
<?
include 'classes.php';
$query="SELECT * FROM Sex_Table";
$result=mysql_query($query);
?>
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()">
<option>Select Colour Type</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['ID']?> sex_price="<?=$row['Price']?>"><?=$row['Sex_Name']?> (£<?=$row['Price']?>)</option>
<? } ?>
</select><br /><br />
<p id="Clothingdiv">
<select style="width: 300px;" name="Clothing" disabled='disabled'>
<option>Select Sex First</option>
</select>
</p><br />
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true}); </script>
</form>
and here's my js:
function changePrice() {
var sex_price = $("option:selected").attr("sex_price");
$("#price_div").html("Price = £" + sex_price);
}
Thanks
Below is an example of what you're trying to do, I've given each select element I want to calculate the total for a class so that they are not mixed up with other elements.
jQuery
<script>
$(document).ready(function() {
$('.calculate').change(function() {
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
$('#total').text('£' + total.toFixed(2));
});
});
</script>
HTML
<select class="calculate" name="select-1">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-2">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<select class="calculate" name="select-3">
<option value="0">Please Select</option>
<option value="1.99">£1.99</option>
<option value="2.99">£2.99</option>
</select>
<span id="total">£0</span>
This will update the contents of total with the total price of each select element with class calculate when one of them is changed.
select with multiple should have the size attribute set as well, like this:
<select data-placeholder="Your Favorite Football Team" class="chzn-select" multiple="multiple" tabindex="6" id="Sexdiv" name="Sexdiv" style="width: 300px;" onChange="getClothing(this.value),changePrice()" size="10">
Your jQuery script:
$('select#Sexdiv').change(function() {
var value = 0;
$("select#Sexdiv option:selected").each(function(){
value += parseFloat($(this).val());
});
$("#price_div").html("Price = £" + value);
});
Hmm?

How do i create a dropdown menu which puts data from an array in a textfield

I want to add this functionality to my form. when a option from a dropdown menu is selected i want it to input the text field above with the corresponding info.
objBMW = {
"Sedan":"5-series",
"Convertible":"6-series",
"Truck":"X5",
"Coupe":"3-series",
"Hatchback":"5-series GT"
};
<form name="form1" action="formhandler">
<input type="text" name="typecar">
<select name="BMWCars">
<option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above
<option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above
<option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above
<option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above
<option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above
</select>
Javascript:
document.forms.form1.BMWCars.onchange = function(){
document.forms.form1.typecar.value = objBMW[this.value];
}
http://jsfiddle.net/xZsc7/
I would do it like this:
<input type="text" name="typecar" id="typecar" />
<?php
$objBMW = array('Sedan' => '5-series', 'Convertible' => '6-series');
?>
<select name="BMWCars" id="BMWCars">
<?php
foreach($objBMW as $key => $value)
{
echo '<option value="'.$value.'">'.$key.'</option>';
}
?>
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#BMWCars').change(function() {
$('#typecar').val($("#BMWCars option:selected").val());
}).trigger('change');
});
</script>

Show/hide fields depending on select value

I am trying to show and hide a few form fields depending on the value of one of my select fields. I am looking to use arrays to hold what should be shown and what should not be shown for each select value, to save me from a massive switch statement, but cannot figure out how to do it.
I am using PHP and jQuery. Any help would be great.
Try something like this:
<select id="viewSelector">
<option value="0">-- Select a View --</option>
<option value="view1">view1</option>
<option value="view2">view2</option>
<option value="view3">view3</option>
</select>
<div id="view1">
<!-- content -->
</div>
<div id="view2a">
<!-- content -->
</div>
<div id="view2b">
<!-- content -->
</div>
<div id="view3">
<!-- content -->
</div>
then in the jQuery:
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
});
});
There are a few different ways you could do this. The simplest is to have a few separate fieldsets, each one containing a single group of fields. Then, in jQuery, dependent on the select-menu's value you can show/hide these fieldsets, e.g.
<fieldset id="f1">
<input name="something1" />
<input name="something2" />
<input name="something3" />
</fieldset>
<fieldset id="f2">
<input name="something4" />
<input name="something5" />
<input name="something6" />
</fieldset>
<select name="fieldset-choice">
<option value="f1">Fieldset 1</option>
<option value="f2">Fieldset 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=fieldset-choice]').change(function(){
var fieldsetName = $(this).val();
$('fieldset').hide().filter('#' + fieldsetName).show();
});
// We need to hide all fieldsets except the first:
$('fieldset').hide().filter('#f1').show();
</script>
Note: For the above technique to be entirely unobtrusive you might want to dynamically build the select-menu with the names of all the different fieldsets.
Alternatively you can prefix each fields name with a meaningful prefix, and then hide/show according to that attribute:
<input name="group1-name1" />
<input name="group1-name2" />
<input name="group2-name3" />
<input name="group2-name4" />
<input name="group2-name5" />
<select name="field-choice">
<option value="group1">Group 1</option>
<option value="group2">Group 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=field-choice]').change(function(){
var groupName = $(this).val();
$('input').hide().filter('[name^=' + groupName + ']').show();
});
// We need to hide all fields except those of the first group:
$('input').hide().filter('[name^=group1]').show();
</script>
To fire up the code on load, just add .change(). As shown below...
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
}).change();
});
My 2 cents :
I needed to show/hide fields depending on many previous select value (not only one).
So I add a parent attribute to div fields like this :
<div id="view" parent="none">
<select class=selector id="view">
<option value="0"> -- Make a choice --</option>
<option value="s1">sub 1</option>
<option value="s2">sub 2</option>
<option value="s3">sub 3</option>
</select>
</div>
<!-- you need to define the parent value with the value of parent div id -->
<div id="s1" parent="view">
<!-- if you want to have a selector be sure it has the same id as the div -->
<select class=selector id="s1">
<option value="0">-- Make a choice --</option>
<option value="s1_sub1">sub 1 of s1</option>
<option value="s1_sub2">sub 2 of s1</option>
<option value="s1_sub3">sub 3 of s1</option>
</select>
</div>
<!-- Make the same thing for s2 and s3
Define div s2 here
Define div s3 here
-->
<!-- and finally if that's your final step you put what you want in the div -->
<div id="s1_sub1" parent="s1">
You are inside s1 sub1
</div>
Now the jquery code :
$(document).ready(function() {
$('select[class=selector]').change(function() {
//next div to show
var selectorActive = $(this).val();
//div where you are
var parentValue = $(this).attr("id");
//show active div and hide others
$('div').hide().filter('#' + selectorActive).show();
while (parentValue!="none") {
//then show parents of active div
$('div[id=' + parentValue + ']').show();
//return the parent of div until "none"
parentValue = $('div[id=' + parentValue + ']').attr("parent");
}
});
// print only the first div at start
$('div').hide().filter("#view").show();
});
That's works like a charm and you don't need to define maps
I hope this will help
#Martin Try this
`$('#viewSelector').trigger('change');`
Here is a very simple example:
The purpose is to show A SIMPLE EXAMPLE of how to use an array of values to show/hide fields depending upon the value of a select.
In this demo, I could have used the classNames to show/hide the group of fields all-at-once -- but that's not the purpose of the example -- so the classNames were used only for CSS.
Because the demo uses IDs (with two arrays of these IDs) for the demo, it doesn't matter whether the fields to be hidden are input fields, divs, imgs or what-have-you. The ID identifies whatever-it-is-to-be-hid.
var aPeople = ['bob','sam','ted'];
var aTransport = ['car','bike','truck'];
$('#mySel').change(function(){
$('.alldiv').hide(); //Hide them all to start...
let sel = $(this).val(); //Get selected option value
if ( sel=='ppl' ){
for (let i=0; i<aPeople.length;i++){
$('#' + aPeople[i]).show();
}
}else if ( sel=='tpt' ){
for (let i=0; i<aTransport.length;i++){
$('#' + aTransport[i]).show();
}
}else{
//Choose selected
$('.alldiv').show();
}
});
.alldiv{width:30vw;height:10vh;padding:2vh 2vw;text-align:center;}
.ppl{background:palegreen;}
.tpt{background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="mySel">
<option value="">Choose:</option>
<option value="ppl">People</option>
<option value="tpt">Vehicles</option>
</select>
<div id="bob" class="alldiv ppl">People: Bob</div>
<div id="car" class="alldiv tpt">Vehicle: Car</div>
<div id="truck" class="alldiv tpt">Vehicle: Truck</div>
<div id="sam" class="alldiv ppl">People: Sam</div>
<div id="ted" class="alldiv ppl">People: Ted</div>
<div id="bike" class="alldiv tpt">Vehicle: Bike</div>

Categories