I got a project using asp.net core 3.1 MVC.
It contains a form with a selection that is disabled.
<div class="col-12 mb-3">
<select asp-for="SelectableItem" class="multi-select form-control" id="selectedItem" disabled="disabled" required="required">
<option value="">-- Select Item --</option>
</select>
<span asp-validation-for="SelectableItems" class="text-danger"></span>
</div>
The fully rendered html
<select class="multi-select form-control" id="selectedItem" disabled="" required="required"
data-val="true" data-val-required="Selected Item is required"
name="SelectedItem">
<option value="">-- Select Item --</option>
</select>
This selection is disabled until the user checks a box, which then populates the select element and enables it, as the content depens on wat checkbox has been selected.
When the user tries to submit the form the validation of JQuery.Validation.Unobtrusive validates everything except that disabled field, as the field is required however i would like for it to be validated as well.
I only want it to be enabled for that one form, so not all disabled elements throughout the application, but can't seem to get it to work.
I tried the following and some variants of it.
$('form').validator.setDefaults({ignore: null})
$('form').data('validator').settings.ignore = "";
$('form').validator.setDefaults({ignore: []})
$('#selectableItem').Validate().settings.not('[disabled]')
Non of these seem to do anything, the disabled select refuses to get validated, and all other suggestions like readonly doesn't work on select elements, nor do i want it to be globally allowed, as that would mess up some other forms.
If you really want to validate all disabled form fields, the relevant line in the plugin is:
.not( ":submit, :reset, :image, :disabled" )
Follow the steps:
1.Find the jquery.validate.js in your project.
2.Open the js and press ctrl + F to find the line contains disabled,them comment on this line(or you could remove the :disabled in this line):
3.If you use the default asp.net core project,remember to change the _ValidationScriptsPartial.cshtml.Because this view add a reference for jquery.validate.min.js,but you modify the jquery.validate.js(If you still want to use min.js,please read the docs and learn how to bundle and minify static assets ):
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script> //change here...
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
Here is a working demo:
Model(add [Required]attribute):
public class Test
{
[Required] //add this
public string SelectableItem { get; set; }
}
View(remove required="required"):
#model Test
<form method="post">
<input type="checkbox" />
<div class="col-12 mb-3">
<select asp-for="SelectableItem" class="multi-select form-control" id="selectedItem" disabled="disabled">
<option value="">-- Select Item --</option>
</select>
<span asp-validation-for="SelectableItem" class="text-danger"></span>
</div>
<input type="submit" value="Create" />
</form>
#section Scripts
{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(document).ready(function () {
$('input:checkbox').change(function () {
if (this.checked) {
//add to select list
$("#selectedItem").append($("<option></option>")
.attr("value", "1")
.text("aa"));
$("#selectedItem").append($("<option></option>")
.attr("value", "2")
.text("bb"));
$("#selectedItem").append($("<option></option>")
.attr("value", "3")
.text("cc"));
// $("selectedItem").prop('required', true);
$("#selectedItem").removeAttr('disabled');
}
else {
//remove item from select list
$("#selectedItem").empty().append($("<option></option>")
.attr("value", "")
.text("-- Select Item --"));
$("#selectedItem").prop('disabled', true);
}
});
});
</script>
}
Result:
Related
I'm trying to show my "Embossing" textbox only when the "Style" dropdown option "Embossing" is selected. I've added the below code in my new template, product-customizable-template.liquid, which created the textbox but I want to hide it unless "Embossing" is selected.
<p class="line-item-property__field">
<label for="embossing">Embossing</label>
<input required class="required" id="embossing" type="text" name="properties[Embossing]">
</p>
"Style" Dropdown
The Style textbox has the following code:
<select class="single-option-selector single-option-selector-product-customizable-template product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="None" selected="selected">None</option>
<option value="Embossing">Embossing</option>
<option value="Stamp">Stamp</option>
</select>
I am still working on the site, so it is not active right now.
Any help would be greatly appreciated, thank you!
You need to check on-page load and on change of select box using Javascript and you can add and remove custom code to form easily
You can check and try the below snippet for a better idea
// on change test for your condition
document.getElementById('SingleOptionSelector-0').addEventListener('change', function (e) {
_checkAndAppend();
});
// run on page load and check the for value and add if selected value meet condition
_checkAndAppend();
function _checkAndAppend() {
var item = document.getElementById('SingleOptionSelector-0');
var itemValue = document.getElementById('SingleOptionSelector-0').value;
if (itemValue == 'Embossing') {
var input = `<p class="line-item-property__field _embossing">
<label for="embossing">Embossing</label>
<input required class="required" id="embossing" type="text" name="properties[Embossing]">
</p> `;
item.parentNode.insertAdjacentHTML('beforeend',input);
} else {
if(document.querySelector('._embossing')){
document.querySelector('._embossing').remove();
}
}
}
I have some code that gets a value from unselected options in a select dropdown. This displays in console.log as an array with the correct values. However, serialize(); is not returning any values for this select when i console.log(data);. If I console.log(boxintake); this shows me the correct values being passed.
Options are being added from button click and are working correctly. Assume all names and form names are correct.
I would be grateful if someone could enlighten me as to why this is not working. Many thanks.
html
<div class="form-group">
<label class="labelStyle" for="box_ni">Select Your Box(es)</label><br />
<select disabled id="box_ni" multiple name="box_ni[]" size="15">
<option value="">
</option>
</select>
<div id="nidstrmessage"></div>
<div class="servicesHelp"><lead id="serviceHelp" class="form-text text-muted help">
Read help <img src="/domain/admin/images/qmark.png" width="24px" height="24px" class="helpintk"/>
</lead>
</div>
<div class="noBrtvBoxes" style="color:white;"></div>
</div>
js
$("#USRboxni").submit(function(e) {
e.preventDefault();
var boxintake = $("#box_ni option").map(function(){
return this.value;
}).get();
console.log(boxintake);
var data = $("#USRboxni").serialize();
console.log(data);
});
Couple of issues:
.serialize() will exclude any controls that are disabled
.serialize() on a multi select will only return the selected values
As your select is both disabled and doesn't have anything actually selected, you get no results.
When you add your items, I suggest you also make them selected at that time; this might solve many of your issues.
That's what <select multiple is for - giving the user a number of options and allowing them to select which ones they want. But you're not using it for that, you're using it as a "the user selected these". You might be better off using a hidden input store and a div to show the selected values.
Example snippet with disabled removed and one item selected shows that it only returns that one item:
//$("#USRboxni").submit(function(e) {
//e.preventDefault();
var boxintake = $("#box_ni option").map(function() {
return this.value;
}).get();
console.log(boxintake);
var data = $("#USRboxni").serialize();
console.log(data);
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='USRboxni'>
<div class="form-group">
<label class="labelStyle" for="box_ni">Select Your Box(es)</label><br />
<select /*disabled*/ id="box_ni" multiple name="box_ni[]" size="15">
<option value="1" selected>one</option>
<option value="2">two</option>
</select>
</div>
</form>
You could remove the 'disabled' just before serialize() then add it back, but you'll still need to select the items.
I have a small form.
Two select box elements and a submit button.
The select box elements collectively when selections are chosen, fire off an ajax request.
What I want to do is, disable the submit button UNTIL user has made selections from the select drop downs.
They must make a selection from BOTH select drop downs, before the Submit button is enabled.
I dont mind if the submit button is hidden until selections made.
Brief Code:
<form id="ad_form" method="post" action="">
<p>
<select id="ad_type" name="ad_type">
<option value="" selected="selected">Select premium ad type</option>
<option value="<?php echo TYPE_USER;?>">Featured Agent</option>
<option value="<?php echo TYPE_LISTING;?>">Featured Listing</option>
</select>
<label for="ad_type" class="labelStrong">Advertising Type</label>
</p>
<p>
<select id="ad_duration" name="ad_duration">
<option value="" selected="selected">Select premium ad duration</option>
<option value="weekly">Weekly</option>
<option value="fortnightly">Fortnightly</option>
<option value="monthly">Monthy</option>
</select>
<label for="ad_duration" class="labelStrong">Advertising Duration</label>
</p>
<p>
<div id="calender">
</div>
</p>
<p>
<input type="submit" name="submit" value="Submit" id="submitorder" />
</p>
</form>
Here's a demo that seems to do what you want:
http://jsfiddle.net/Yr59d/
That javascript code would go in a $(document).ready() block
$(function() {
$("#submitorder").css("visibility", "hidden");
$("#ad_form select").bind("change", function() {
if ($("#ad_type").val().length > 0 && $("#ad_duration").val().length > 0) {
$("#submitorder").css("visibility", "visible");
} else {
$("#submitorder").css("visibility", "hidden");
}
});
});
If you give all your selects a common class name (like 'required') , you can do something like this:
$('select.required').change(function() {
var total = $('select.required').length;
var selected = $('select.required option:selected').length;
$('#submitorder').attr('disabled', (selected == total));
});
This is not tested code. This documentation might help. This jquery discussion might help too.
Gah, I'll have to agree with Kon on this one - fix-now-worry-about-it-later answers have their place but an elegant solution that is simple at the same time has to be the way to go.
My solution: (with credit from a thread at: JQuery Enable / Disable Submit Button in IE7)
$('select.required').change(function() {
var total = = $('select.required').length;
var selected = $('#ad_form').find("select.required option[value!='':selected").length;
$('#submitorder').prop('disabled', (selected != total));
});
Incidentally, thanks ctcherry for demoing the code on the JSFiddle site - I've not seen that before and will make use of it in the future!
Use listeners on both select buttons for change and check whether the other is also set. If set, enable the submit button.
I have two forms and a selector.
This is my code --
<select>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<form id="pp">
<input type="text">
</form>
<form id="cc">
<input type="text">
</form>
Now if option 1 is selected i want to hide form CC. if 2 hide form PP.
How do i do it with js or jquery? thanks
Try this (using jQuery):
$("select").bind("change", function() {
if ($(this).val() == "1") {
$("#pp").show();
$("#cc").hide();
}
else if ($(this).val() == "2") {
$("#pp").hide();
$("#cc").show();
}
});
Additionally, you could hide both forms using .hide() as shown above before the user selects any option.
bind is attaching an event handler to the "change" event of the select box. This is fired when the user changes what option is selected.
Inside the handler, val is used to determine the value of the currently selected option.
show() and hide() are used on the correct forms, depending on which option was selected.
Working example: http://jsfiddle.net/andrewwhitaker/faqZg/
<script>
function Hide(val)
{
if(val==1)
{
document.getElementById('cc').style.display='none';
document.getElementById('pp').style.display='inline';
}
if(val==2)
{
document.getElementById('pp').style.display='none';
document.getElementById('cc').style.display='inline';
}
}
</script>
<select onchange="Hide(this.value);">
<option value="">Please Select</option>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<div id="pp">
<input type="text">
</div>
<div id="cc">
<input type="text">
</div>
Yup, basically, I am building a web form that need to provide different required form and validation function fallow by selected country.
I am using
<script type="text/javascript" src=" jquery-1.3.2.min.js" charset="utf-8"></script>
<script type="text/javascript" src=" jquery.validate.js" charset="utf-8"></script>
and here is my JS code
<script type="text/javascript" charset="utf-8">
function updatRequreForm (STATE,ZIPCODE) {
$("#frm_verification").validate({
rules: {
'form[country]' : "required",
'form[state]' : {required: STATE},
'form[zip]': {required: ZIPCODE},
},
messages: {
'form[country]' : "This field is required.",
'form[state]' : "This field is required.",
'form[zip]': "This field is required.",
});
};
function setRequreForm () {
var _cs = $('#country_select')[0];
if ('US' != _cs.value)
{
$('#state_star')[0].innerHTML = '';
$('#zip_star')[0].innerHTML = '';
updatRequreForm (false,false);
}
else
{
$('#state_star')[0].innerHTML = '*';
$('#zip_star')[0].innerHTML = '*';
updatRequreForm (true,true);
}
};
$(document).ready(function() {
setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
</script>
Here is my HTML:
<form id="frm_verification" action="some.php" method="POST">
<label for="country_select"><sup>*</sup>Country:</label>
<select name="form[country]" id="country_select">
<option value="">- Select -</option>
<option value="US" selected="selected">United States</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
<label for="select-state"><sup id="state_star">*</sup>State/Province/Region:</label>
<span id="states_select">
<select id="select-state" name="form[state]">
<option value="">- Select -</option>
<option value="AK">Alaska</option>
</select>
</span>
<span id="states_text" style="display:none;">
<input type="text" name="form[state]" value="" id="state" />
</span>
<label for="zip_code"><sup id="zip_star">*</sup>ZIP/Postal Code:</label>
<input type="text" id="zip_code" name="form[zip]" value="" id="zip">
<input type="submit" value="Submit" id="submit_btn" class="submit">
</form>
Basically, what I need to create is:
1.When user select US on country selection, the State and Zip area become required.
2.When user select Zambia on country selection, the State and Zip area become non-required.
Problem:
When I first load the page and click the Submit button with empty field, the form successfully validate each fields and shows warning. However selecting of the Zambia, the validation is not working.
Guess:
I have removed “setRequreForm ();” on ready function like:
$(document).ready(function() {
//setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
And tried to select Zambia, and tried to validate the form and it works. So I think calling “validate()” twice causes error.
Well I stuck with this for a while. Please help me to figure this out, I will really appreciate that.
You can't call validate more than ones becouse you run validate plugin more than one and this lead to errors.
You can setup your validator like this:
$("#myform").validate({
ignore: ".ignore"
})
Ignore tells to validator: field which has ignore css class should not be validated.
When you change requirements then add to specified fields css class "ignore":
$("#field1").addClass("ignore");
otherwise remove this class:
$("#field2").removeClass("ignore");