HTML
<select name="CustomerType" id="CustomerType" class="form-control" onchange="CustomerTypeChange()">
<option value="#((int)THOS.Utilities.Enumerations.Enumerations.Customer.CustomerType.Company)" selected="#(Model != null ? (Model.CustomerType == (int)THOS.Utilities.Enumerations.Enumerations.Customer.CustomerType.Company):true)">Company</option>
<option value="#((int)THOS.Utilities.Enumerations.Enumerations.Customer.CustomerType.Person)" selected="#(Model != null ? ((Model.CustomerType == (int)THOS.Utilities.Enumerations.Enumerations.Customer.CustomerType.Person)) : false)">Person</option>
</select>
<input type="text" name="TaxNumber" id="TaxNumber" class="form-control parsley-validated">
When CustomerType change below js code runs
Javascript Code:
function CustomerTypeChange() {
var customerType = document.getElementById("CustomerType").value;
if (customerType == 10) {
$('#TaxNumber').attr("data-required", 'false');
}
if (customerType == 20) {
$("#TaxNumber").attr("data-required", 'true');
}
}
When i add TaxNumber attribute true/false attr("data-required", true) or attr("data-required", false) never works .
Edited:
$("#TaxNumber").data('data-required', true); does not work too
$("#TaxNumber").data('required', true); does not work too
If i check browser console there is no any error where i miss exactly ?
Thanks.
Suggested improvements:
When using jQuery avoid connecting events via attributes. Also use jQuery for select value checking (using val()).
Remove the onchange attribute and try this instead:
// Shortcut DOM ready handler
$(function(){
// Listen for change event
$('#CustomerType').change(function(){
// Use jQuery val() to get select values
var customerType = $(this).val();
if (customerType == 10) {
$("#TaxNumber").attr("data-required", 'false');
}
if (customerType == 20) {
$("#TaxNumber").attr("data-required", 'true');
}
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/CmW9e/1/
If you inspect the DOM you will see the data-required attribute is set correctly.
Your original "works" too:
Your original code also works: http://jsfiddle.net/TrueBlueAussie/CmW9e/2/ so it is more likely the problem that your validation framework does not pickup dynamic changes to the required flag. Is the issue actually that you expected the validation rules to update automatically based on that attribute?
Solution:
Most validation frameworks allow you to change the rules client-side (add and remove rules etc), but you will need to provide details of the validation framework you are using to get a specific answer :)
Related
I'm trying to disable a button for prevent adding new rows in table.
My problem is that prop() method work fine, but doesn't disable button (I can't add new rows, its worked fine, but button still click and looks like "active" (and attribute "disabled" not added to my button)).
If I use attr("disabled", "disabled") instead of prop("disabled", true) that works fine and button disabling (attribute "disabled" added to element), but I read what to use attr() is bad after JQuery 1.6+.
var addBtn = $(".k-grid-add");
addBtn.bind("click", function () {
if (grid.dataSource.data().length == 9) {
$(addBtn).prop("disabled", true); // <- work, but button still "active"
// $(addBtn).attr("disabled", "disabled"); // <- work fine
}
What am I doing wrong? Thanks!
Since disabled is a Boolean attribute, you need to set it like disabled="disabled":
$(addBtn).prop("disabled", "disabled");
It is working for me ! Just look what I tested ....
addBtn = $("#btn");
addBtn.prop("disabled", true);
addBtn.on("click",function() { console.log(999); });
//
enable.onclick = function() {
addBtn.prop("disabled", false);
}
//
disable.onclick = function() {
addBtn.prop("disabled", true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">sdf</button>
<button id="enable">Enable</button>
<button id="disable">Disable</button>
I can't verify that, it should work. Here's a part my code, which is working, if I enter more than 6 characters, the buttons are active, if I delete it the buttons get disabled. What version of jQuery do you use? Also, the use of bind is deprecated in jQuery version >3.0, using element.on() will be more future proof (http://api.jquery.com/bind/).
$commentsInput.on('input.UECommenting', function (event) {
let buttonsDisabled = $commentsInput.val().length < 7 ? true : false;
for (let button in $commentingButtons) {
$commentingButtons[button].prop({ 'disabled': buttonsDisabled, 'title': buttonsDisabled ? 'No comments without content!' : '' });
}
});
And I have to recommend getting used to use namespaces for events, with that you can easily use element.off('.namespace') to ensure that your events wont be setted and fired multiple times.
Good day,
In my code, I need to use a drop-down list that has two values, say 1 and 2. When I click the #action-link link I append the corresponding text of the value into a textarea (#main-reply). I use Jquery .change() method to determine when selected value changed. Works ok unless I switch options several times and then it starts to add multiple values at a time even though I need insert in textarea only the corresponding value.
Here is a simple snippet of the code I use:
$("#action-link").click(function() {
if ($("#option").val() == 1) {
$("#main-reply").append("One");
}
});
$("#option").change(function() {
if ($(this).val() == 2) {
$("#action-link").click(function() {
$("#main-reply").append("Two");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="option"><option value='1' selected>One</option><option value='2'>Two</option></select>
Add Value to textarea
<br>
<textarea id="main-reply"></textarea>
How can I solve this? Thanks!
Code adds another on-click listener when the value of the option was changed to '2' Link. Therefore the append() statament was being called multiple times, one from each listener.
$("#action-link").click(function() {
var option = $("#option").val();
if (option == 1) $("#main-reply").append("One");
else if(option == 2) $("#main-reply").append("Two");
});
Most of the times, this issue occurs when you load the same js file twice.
When JS file gets loaded twice, 2 on change events will get attached to the same event. Hence the actions will happen twice
Check your code and make sure that the JS file is not loaded twice
If it's not loaded twice and somehow this issue is still occurring, then use below code
$("#option").off().on("change",function() {
if ($(this).val() == 2) {
$("#action-link").click(function() {
$("#main-reply").append("Two");
});
}
});
This will remove any events attached to the change event and then adds the function
In your code click event is added on every change event for option value 2, which is not a good way as well.
You can write code as below
$("#action-link").click(function() {
if ($("#option").val() == 1) {
$("#main-reply").append("One");
} else if ($("#option").val() == 2) {
$("#main-reply").append("Two");
}
});
$("#option").change(function() {
// Just trigger click on change which handle other stuff
$("#action-link").trigger("click);
// You can write use below code as well.
// $("#action-link").click();
});
OR you can make it very simple as below which is dynamic regardless of any option value which will adds selected option value.
$("#action-link").click(function() {
appendOptionValue($("#option").val());
});
$("#option").change(function() {
appendOptionValue($("#option").val());
});
function appendOptionValue(optionValue){
$("#main-reply").append(optionValue);
}
this is it :
var val = $("#option").val();
$("#action-link").click(function() {
$("#main-reply").append(val);
});
$("#option").change(function() {
val = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="option">
<option value='One' selected>One</option>
<option value='Two'>Two</option>
</select>
Add Value to textarea
<br>
<textarea id="main-reply"></textarea>
this might helpful to you. Use text() instead of append
$(document).ready(function(){
$('#action-link').click(function(event) {
if($('#option').val()==1){
$('#main-reply').text('one');
}else{
$('#main-reply').text('two');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="option"><option value='1' selected>One</option><option value='2'>Two</option></select>
Add Value to textarea
<br>
<textarea id="main-reply"></textarea>
I have the following select box:
<select id="choose">
<option value=1>A</option>
<option value=2>B</option>
<option value=3>C</option>
</select>
<div id="hide-me">hide me!</div>
How can I hide an element when I select option "B"? I tried this:
<script type="text/javascript">
if ("#chose option:selected").val(2) {
$("#hide-me").hide();
};
</script>
I think I'm close, but nothing happens when I select option "B". Anyone have any suggestions?
You need to attach change event to select element to detect the option change. then use .toggle() with argument value not equal to 2 for making show/hide decision :
$('#choose').change(function(){
$("#hide-me").toggle($(this).val() != "2");
})
Working Demo
Listen to the change event of the #choose element, and add your conditional logic there.
Example Here
$('#choose').on('change', function () {
if (this.value === "2") {
$("#hide-me").hide();
} else {
$("#hide-me").show();
}
});
..equivalent, but perhaps less readable version:
Example Here
$('#choose').on('change', function () {
$("#hide-me").toggle(this.value !== "2");
});
As a side note, the value of the selected option is a string.
If you wanted to, you could also convert it to a number:
if (parseInt(this.value, 10) === 2) { ... }
or you could use == rather than ===: (not suggested, though. This could lead to logical errors.)
if (this.value == 2) { ... }
Without jQuery:
Example Here
document.querySelector('#choose').addEventListener('change', function () {
var element = document.getElementById('hide-me');
if (this.value === "2") {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
});
The problem with your code is that:
It is not syntactilally correct — ("#chose option:selected").val(2) is an expression, which in turn should be wrapped in parentheses to be a proper condition for if, like this:
if (("#chose option:selected").val(2)) {
However, even after that your code is not correct because you're not actually using jQuery. You're calling method .val() just on a string "#chose option:selected", whereas that string should instead be a jQuery selector passed to jQuery itself:
if ($("#chose option:selected").val(2)) { // $ is the jQuery object that does all the work
However2, even that is incorrect, because you'd just be checking the value of an element right away. What you need is to wait for an element to be changed. Other answers explain very well how to do that.
I have a few input fields that must be filled before some button becomes active. My code does this, but only works after filling all inputs fields I changed selection from last filled input field to any other. How to make it more dynamic and allow button to become active without changing selection?
$(function() {
$('body').on('change','#form2',function(){
if($("#name").val() != "" && $("#number").val() != "" && $("#shortname").val() != "")
{
$('#CreateConnections').removeAttr("disabled");
}
else
{
$('#CreateConnections').attr("disabled", true);
}
});
})
You can try binding both keyup and change to all input elements. Also:
instead of using != to evaluate the value, we can simply check the value itself: when not empty it will return true, without the need to make comparisons.
you should use .prop() when working with boolean attributes, like disabled, checked, readonly, selected and the likes, instead of .attr(). p/s: You should also avoid using .removeProp() or .removeAttr() whenever possible, as once removed they cannot be added back.
Here is the updated jQuery:
$(function() {
$('body').on('change keyup','#form2 :input', function() {
if($("#name").val() && $("#number").val() && $("#shortname").val()) {
$('#CreateConnections').prop("disabled", false);
} else {
$('#CreateConnections').prop("disabled", true);
}
});
});
Here is a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/7rK2p/
I've got a select list that looks like this:
<select id="ListingType" name="Criteria/ListingTypeID" onchange="Search.toggleListingType(this);">
<option selected="selected" value="1">RH1</option>
<option value="2">BC4</option>
<option value="3">RR3</option>
<option value="4">RH2</option>
<option value="5">RE0</option>
</select>
I'm trying to set the value to 3. I've unsuccessfully tried 3 ways to do this.
1.
this.evaluate(function(value) {
document.querySelector('select#ListingType').value = value;
return true;
}, '3');
// insure the onChange JS is run
this.evaluate(function() {
var element = document.querySelector('select#ListingType');
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', false, true);
element.dispatchEvent(evt);
});
This appears to work (throws no errors), but the value doesn't get changed.
2.
this.fillSelectors('select#ListingType', {
'select[name="Criteria/ListingTypeID"]' : "3"
}, true);
This throws the error message: ``CasperError: Errors encountered while filling form: no field matching css selector "select[name="Criteria/ListingTypeID"]" in form''
What's wrong with my selector?
3.
// In desperation...
this.sendKeys('select#ListingType', 'RR3');
This also seems to work (no errors), but again the value is unchanged.
Just for completeness, I've tried sending the "change" event after each of the variations. I also dump out the attributes of the selected element after each, and it never shows the value as being set.
Note the page that this selector is on has a ton of JS code on it, and this <select> element is not wrapped in a <form> element.
I'm sure I'm making some really stupid mistake, but after hacking on this code for the last several days, I've not made any progress. What's a working way to do this?
You can use slimerJS (it opens firefox) to easily check a change in value.
this.fillSelectors('form#id_form', {
'select[name="Criteria/ListingTypeID"]' : "3"
}, false);
this.wait(6000,function(){
this.echo("i saw my new value");
});
And if you want to fill the option by its text and not value (i find it easier): use this function :
casper.fillSelectOptionByText = function (selectSelector,text){
this.evaluate(function(sel,setByText) {
$(sel + " > option").each(function() {
if($(this).text() === setByText) {
$(this).attr('selected', 'selected');
}
});
},selectSelector,text);
};
And in your test :
this.fillSelectOptionByText("select[name='year of birth']","1991");
The page has to have jquery of course, or you inject it.