Show/hide a select field on Edit page, based on database value - javascript

In one of "Add product" page, I've select field that shows/hides based on what we select on another select field. This is the code:
$(function() {
$('#warranty_periods').show();
$('#warranty_type').change(function(){
if($('#warranty_type').val() == '1') {
$('#warranty_periods').show();
} else {
$('#warranty_periods').hide();
}
});
});
My problem is how to hide it on the edit page if "warranty_type" was other than '1' while adding the product.
Thanks

If you want the same logic to be invoked when the page loads, then do exactly that. For example, you can define a function that you would use for the event you currently have as well as be immediately invoked. Something like this:
$(function() {
var toggleWarrantyPeriod = function(){
if($('#warranty_type').val() == '1') {
$('#warranty_periods').show();
} else {
$('#warranty_periods').hide();
}
};
toggleWarrantyPeriod();
$('#warranty_type').change(toggleWarrantyPeriod);
});

Try to logout the value of warranty_type using
console.log($('#warranty_type').val());
Check if you are getting the desired value

Related

Display Error Message For Select If Expand Then Closed Without Selection Made In JQuery

I have a select and i'm after displaying an error message as soon as the user expands the select and closes it without making a selection but i cant figure how to do this.
I have it validating on.change if the val matches the default as shown below
Working JQuery When An Option Is Selected
$('#orderPosition').change(
function () {
if ($('#orderPosition').val() == 'orderPositionDefault') {
$('#orderErrorMessage').show();
$('#orderPosition').focus();
$('#orderPosition').css("background-color", "lightcoral");
} else {
$('#orderErrorMessage').hide();
$('#orderPosition').css("background-color", "transparent");
}
}
);
I have tried the following
$('#orderPosition').on('click', function () {
// var isDirty = !this.options[this.selectedIndex].defaultSelected;
var changed = $(this).val() != $(this).data('orderPositionDefault');
alert(changed ? 'changed' : 'not changed');
if (changed) {
$('#orderErrorMessage').show();
} else {
$('#orderErrorMessage').hide();
}
});
But the issue with the above is as soon as i click in the select the error message is displayed, i need it to be displayed of the user clicks in it and closes it straight away without making a selection.
Use the blur event for executing code when focus leaves on an input field.
$('select').on('change', function() {
//change things here
}).on('blur', function() {
//when select is no longer in focus here
});
Documentation: https://www.w3schools.com/tags/ev_onblur.asp

How to get onclick event for jQuery Chosen drodpown listbox?

Hi I am developing one jquery application. I ghave one dropdownbox with jquery choosen.
$(function () {
$(".limitedNumbSelect").chosen();
});
This is my dropdown and binding values from database.
<b>Awarded To:</b> <asp:ListBox ID="ddlvendorss" runat="server" SelectionMode="Multiple" class="limitedNumbSelect"></asp:ListBox>
I am trying to get click event for the above dropdown. As soon as i click on the dropodwn i want to fire a alert before loading any options.
$('#ddlvendorss').click(function (e) {
alert("I am going crazy");
});
In the below code checkedValues arrays contains some values(values present in dropdownlistbox). As soon as i click on the drodpown i ant to hide those values. But below code doesnt work.
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
$(".limitedNumbSelect option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
Above code does not work. May I get some advise on this? Any help would be appreciated. Thank you.
Chosen hides the select element, thus you are not actually clicking the element. However you can use chosen:showing_dropdown event
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
alert('No need to go crazy');;
});
Fiddle
If you want to hide options, You can use
$(".chzn-select").chosen().on('chosen:showing_dropdown', function() {
//Find options and hide
$(this).find('option:lt(3)').hide();
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
Fiddle
As per OP's code
$(".chzn-select").chosen().on('chosen:showing_dropdown', function () {
//Get all options
var options = $(this).find('option');
//Show all
options.show();
//Hide based on condtion
options.filter(function () {
return checkedValues.indexOf($(this).val()) === -1;
});
//Update chosen
$(this).chosen().trigger("chosen:updated");
});
instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));

find select option with selected property using javascript

I have a view that loads select elements dynamically into the page on certain button clicks. Each of these selects have the same id value followed with an index value based on how many times the button is clicked. so the id would be like
id="my_id_" + numOfClicks;
I have also given all these selectors the same class value
class="selects"
What is the best way to have an event handler for when the selected option changes in any of the drop downs. right now I have the following:
$('.selects').change(function() {
if($('this option:selected').val() == 0) {
}
else {
}
});
So what I'm trying to do is first get the right select element using "this" then figure out which of the options are selected. Is there a better/more efficient way to do this?
As you say these get added at runtime, you'll want a delegated event handler. Within the handler, as the comments have pointed out, it's just $(this).val() to get the selected value of that select box. So:
$("selector for some container they're in").on("change", ".selects", function() {
if($(this).val() == 0) {
}
else {
}
});
For instance, if they're all inside an element with the class container, then:
$(".container").on("change", ".selects", function() {
if($(this).val() == 0) {
}
else {
}
});
If there's no other suitable container, you can just use $(document).on(..., but usually it's better to handle things a bit closer to where they are than that.
Side note: Values are always strings, but == will coerce, so "0" == 0 is true. Still, it's useful to remember that they're strings.
Assuming html input.selects:
$('body').on('change', '.selects', function() {
if($(this).val() == '0') {
}
else {
}
});
http://jsfiddle.net/r4pxx0yy/1/
No quote around this.

Jquery checkbox on select add a name attribute and increment on more than one selection

Ok,i am building a fantansy football game using codeigniter , Grocery CRUD and Jquery. I have a view where user select 15 players from checkboxes where i will use the name attribute to select GK1,GK2,DEF1,DEF2,DEF3,DEF4,DEF5,MID1,MID2,MID3,MID4,MID5,FWD1,FWD2 and FWD3 and pass their value to the controller. My question is , how do i create a javascript Jquery Code for maybe Midfielders (MID) in such a way that when a user click the first Midfielder the javascript append input name="MID1" and on checking another box it becomes input name="MID2" without changing the name for MID1. So far i the javascript is working but when i click another player the name value changes in all players also if i deselect the name player for that particular player doesnt remove. Here is my JS..
<script>
$(document).ready(function(){
$(".gk").change(function() {
var number=$('[class="gk"]:checked').length;
if(this.checked) {
$(".gk").each(function() {
$(".gk").attr('name',"GK"+number);
});
} else {
$('.gk').attr('name', number);
}
});
});
</script>
and here is my view
<input type="checkbox" class="gk" value="<?=$row->playerID ?>" > <?= $row->playerID?> </input>
Regarding your issue of all players having their name changed, the culprit may be '.each()'. Isn't it supposed to be more like :
$(".gk").change(function() {
if(this.checked) {
var number=$('[class="gk"]:checked').length;
// $(".gk").each(function() {
$(this).attr('name',"GK"+number);
// });
Among other things, you have a problem when you deselect the players, since you are only running that piece of code that updates the name when the $(".gk") is checked... also, in order to add a different number to each one, you'll have to increment an index value, for example, and add it to the name, not the variable number, which will be the size of the selected elements... On top of this, the last variable "number" should be outside of the "if" otherwise you won't see it in the else...
Check this, see if it helps
$(document).ready(function(){
$(".gk").change(function() {
var checked=$('[class="gk"]:checked').length;
alert("You have "+checked+" Gks checked")
var index = 1;
$(".gk").each(function() {
if($(this).prop('checked')){
$(this).attr('name',"GK"+index);
alert("Getting GK "+index)
alert("this GK name is "+$(this).attr('name')
index++;
}
else {
$('.gk').attr('name',"");
}
});
});
});
http://jsfiddle.net/xn3P9/5/
Once you update the name it won't show on the page inspector.
You final solution should be this:
$(document).ready(function(){
$(".gk").change(function() {
var index = 1;
$(".gk").each(function() {
if($(this).prop('checked')){
$(this).attr('name',"GK"+index);
index++;
}
else {
$('.gk').attr('name',"");
}
});
});
});
I still have a hard time understanding what you are looking for but maybe it is something similar to this:
$(document).ready(function(){
$(".gk").change(function() {
$(".gk:checked").each(function(index, gk) {
//Will give each selected GK a unique name
$(".gk:checked").attr("name", "GK"+index);
});
});
});

Enabling checkbox with different elements

Ok, I've been coding a website for a while now and this the first "insurmountable" problem I haven't found an aswer for, so now I'm turning to you, the experts.
On my form I have three drop-down menus, one textbox and one disabled checkbox. I want it to work so that when a user has selected an option from each drop-down menu and written something on the textbox, the checkbox becomes enabled.
I have found this code when I have been looking for a solution and it's very similar to my problem. However, when I try to add another drop-down menu, it still enables the button when I select an option from the first menu and completely ignores the second menu. I'm sorry, I'm new to Jquery/JavaScript and I just think it should work that way when the class names are same on both menus (jQuery class selector: ('.dropdown')).
I have also found a similar code with textboxes. I just don't know how to combine these codes so it would act the way I want.
See it here: http://jsfiddle.net/JKmkL/109/
$(document).ready(function() {
$('.required').change(function() {
var done=true;
$('.required').each(function(){
if(!$(this).val()){
$('.myCheckBox').prop('disabled',true);
done=false;
return false;
}
});
if(done){$('.myCheckBox').prop('disabled',false);}
});
});
And add class required to the elements.
Edit:
The code above assumes that the default <option> has value="". If not, you can use http://jsfiddle.net/JKmkL/114/
$(document).ready(function() {
$('.required').change(function() {
var done=true;
function quit(){
$('.myCheckBox').prop('disabled',true);
done=false;
return false;
}
$('.required.dropdown').each(function(){
if($(this).children(':selected').hasClass("disablenext")){
return quit();
}
});
$('.required[type=text]').each(function(){
if(!$(this).val()){
return quit();
}
});
if(done){$('.myCheckBox').prop('disabled',false);}
});
});
Edit 2:
If you want to show a div when the checkbox is checked and hide it when the checkbox is disabled, use
JavaScript:
$(document).ready(function() {
$('.required').change(function() {
var done=true;
function quit(){
$('.myCheckBox').prop('disabled',true).removeAttr('checked');
done=false;
$('#div2').addClass('hide');
return false;
}
$('.required.dropdown').each(function(){
if($(this).children(':selected').hasClass("disablenext")){
return quit();
}
});
$('.required[type=text]').each(function(){
if(!$(this).val()){
return quit();
}
});
if(done){$('.myCheckBox').prop('disabled',false);}
});
$('.myCheckBox').click(function(){
$('#div2')[(this.checked?'remove':'add')+'Class']('hide');
});
});
CSS:
.hide{display:none}
See it here: http://jsfiddle.net/JKmkL/133/
I assume that dropdown's default value is value=""
$('#form_submit_button').click(function(){
$('.checkbox').attr('disabled',true);
var all_selected = true;
$('.dropdown').each(function(){
if(!$(this).val())
{
all_selected = false;
}
});
if(!$('#text_box').text())
{
all_selected = false;
}
if(all_selected)
{
$('.checkbox').attr('disabled',false);
}
});
First of all, say the id for the three dropdowns are called d1, d2, and d3; textbox is txt; and checkbox is chk. You can then define a function that determines when the checkbox must be enabled:
function shouldEnableCheckbox() {
var nonEmptyFields = $("#d1,#d2,#d3,#txt").filter(function() {
return this.value;
});
return nonEmptyFields.length == 4;
}
Essentially, you select all 4 elements, filter those that are non-empty, and compare the resulting filtered array with 4. If it is true, it means you should enable the checkbox.
Then, assign the change event handler to all 4 elements, invoke the previous function, and assign the result to the disabled property of the checkbox:
$("#d1,#d2,#d3,#txt").change(function() {
$("#chk").prop("disabled", !shouldEnableCheckbox());
});​
Here's the working DEMO, and another working, more generic DEMO, which uses a class instead of ids to identify the required elements.

Categories