Need help on my jQuery script - javascript

I was able to make a dyanamic dropdown subcategory dependent on the selected category which you can see it here.
Now, my problem is that if the category has defined a selected value upon loading which is defined by a REQUEST, just like this (take note on the posted_parent_id request). How can I make a call on my subcategory file(get_child_categories.php?parent_id=6) if my jQuery is like this below:
$(document).ready(function($) {
var list_target_id = 'list_target'; //first select list ID
var list_select_id = 'list_select'; //second select list ID
var initial_target_html = '<option value="">Please select a subcategory...</option>'; //Initial prompt for target select
$('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option
$('#'+list_select_id).change(function(e) {
//Grab the chosen value on first select list change
var selectvalue = $(this).val();
//Display 'loading' status in the target select list
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
//Display initial prompt in target select if blank value selected
$('#'+list_target_id).html(initial_target_html);
} else {
//Make AJAX request, using the selected value as the GET
$.ajax({url: 'get_child_categories.php?parent_id='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
Does my question is quite clear? I am still learning this kind of stuff right now. There's something to be defined somewhere within the if (selectvalue == "") statement in case the category dropdown was pre-selected upon loading the page?

Simplest way is to trigger the change event manually once the DOM has been loaded.
// Assuming that -1 is the default selected value
var selectvalue = $('#'+list_select_id).val();
if(selectvalue != "-1")
{
$('#'+list_select_id).trigger("change");
}
Append the code to the end of the $(document).ready(function(){ ... })
So, your code becomes the following
$(document).ready(function($) {
var list_target_id = 'list_target'; //first select list ID
var list_select_id = 'list_select'; //second select list ID
var initial_target_html = '<option value="">Please select a subcategory...</option>'; //Initial prompt for target select
$('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option
$('#'+list_select_id).change(function(e) {
// ... your logic here
});
// Check if value is prefilled.
var selectvalue = $('#'+list_select_id).val();
// Assuming that -1 is the default value
if(selectvalue != "-1")
{
$('#'+list_select_id).trigger("change");
}
});

The first thing that you have to do is to move that AJAX functionality out of the .change event.
Change event fires only when the dwopdown value is changed and if the dropdown renders with a value as selected one, it wont be handled by change event.
Make it as a separate function and call that on page load and on .change event.
** NOT A COMPLETE CODE **
$(function(){
var dropdown = $('#'+list_select_id);
if (dropdown.val() !== "") {
initiateAJAX(dropdown.val());
}
dropdown.change(function() {
initiateAJAX(this.value);
});
function initiateAJAX(param) {
}
});

Related

jQuery get / set value of textbox value in a repeater

I have a repeater with textboxes ID="txtBomName" in an ascx page with a value retrieved from datatable on pageload.
the end user can change the value, must be not be null/empty.
I have jquery to check if null/empty on change or blur, produce alert if null then I would like the null value set back to original else set value as user entered.
This does work if, I use the generated control ID i.e:
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName)"
this obviously only works for the the first textbox on the page, as the "ct100" part of the ID changes for each box.
code:
$(document).ready(function () {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").change(function () {
var oldVal = this.getAttribute('value');
if (this.value == null || this.value == "") {
alert("Please ensure the name is not empty");
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(oldVal);
}
else {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(this.value);
}
});
});
so, I changed the code to look for id$=txtBomName and set an alert to (this.id) the id for each box shows correctly, how can I set the value of the textboxes using (this.id).val(oldVal); ?
You need to use:
$(this).val(oldVal);
'this' is a reference to the current object i.e. textArea the abouve code will set the value of the textArea
Try this code
$(document).ready(function () {
// The simplest way is to save the original value using data() when the
// element gets focus.
$("input[id$='txtBomName']").on('focusin', function(){
$(this).data('val', $(this).val());
});
$("input[id$='txtBomName']").change(function () {
var txtBox=$(this);
var prev = txtBox.data('val');
var current = txtBox.val();
if (current) {
txtBox.val(current);
}
else {
alert("Please ensure the name is not empty");
txtBox.val(prev);
}
});
});

How do I prevent duplicate entries in a row at chosen jQuery multiple select?

I have several rows with few select boxes. There are several select boxes in each row with the same content. Every item in the row can only be used once, because every column has a classification. If an item is used in a select box, I want it to be greyed out in the other boxes of the row.
I tried this:
function setChosen() {
var config = {
'.chosen-select' : {},
'.chosen-select-deselect': {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:'95%'}
}
for(var selector in config) {
$(selector).chosen(config[selector]);
}
}
setChosen();
$('.chosen-select').on('change', function() {
var selVal = $(this).val();
var rel = $(this).attr('rel');
$('.'+rel).children('option').each(function() {
if($(this).val() == selVal) {
$(this).attr('disabled',true).siblings().removeAttr('disabled').trigger('chosen:updated');
}
});
});
fiddle
I would do this:
From the select that fires the onchange event we can travel up in the DOM to its parent using jQuery's parent(). Then select all the select elements in that parent. Iterate over each select. First reset the option back to enabled, lastly disable the option that matches the selected value of the select that fired the event.
$('.chosen-select').on('change', function() {
var self = this; //create a reference to the owner of the event.
var selVal = $(this).val(); //selected value
var parent = $(this).parent(); //select parent row
//traverse all children in that row that are selects
parent.children('select').each(function() {
$(this).find("option").attr("disabled", false); //set all disabled attributes to false. Basically a reset!
if (this != self) //skip the select that is the owner of the event
{
//set the other options to disabled that matches the value of the select.
$(this).find("option[value='"+selVal+"']").attr("disabled", true);
}
});
});

Second Select disabled if Option 1 in first Select

I have two select boxes. I need the entire second select box to be disabled until the user selects any option other than the first option in the first select box.
This is my logic but I can't quite execute it.
if
.first-select = option-1
then
.second-select .attr('disabled').
else
.second-select .removeAttr('disabled')
You could use the selectedIndex property:
var
firstSelect = document.querySelector('.first-select'),
secondSelect = document.querySelector('.second-select')
;
function changeHandler() {
secondSelect.disabled = firstSelect.selectedIndex === 0;
}
firstSelect.addEventListener('change', changeHandler);
changeHandler(); // execute the handler once on DOM ready
Or if you are using jQuery:
$('.first-select').on('change', function() {
$('.second-select').prop('disabled', this.selectedIndex === 0);
}).change(); // trigger the event once on DOM ready
You have to do something like this
$("#first_select").on("change",function(){
if(this.selectedIndex != 0){
$("#second_select").removeAttr("disabled");
// or you can do this $("#second_select").prop("disabled",false);
});

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Using JavaScript or jQuery, how do I check if select box matches original value?

Just wondering if there is any way to check if the value of a select box drop-down matches the original value at the time of page load (when the value was set using selected = "yes") ?
I guess I could use PHP to create the original values as JavaScript variables and check against them, but there are a few select boxes and I'm trying to keep the code as concise as possible!
That's not too hard at all. This will keep track of the value for each select on the page:
$(document).ready(function() {
$("select").each(function() {
var originalValue = $(this).val();
$(this).change(function() {
if ($(this).val() != originalValue)
$(this).addClass('value-has-changed-since-page-loaded');
else
$(this).removeClass('value-has-changed-since-page-loaded');
});
});
});
This will apply a new class value-has-changed-since-page-loaded (which presumably you'd rename to something more relevant) to any select box whose value is different than it was when the page loaded.
You can exploit that class whenever it is you're interested in seeing that the value has changed.
$(document).ready(function() {
var initialSelectValue = $('#yourselect').val();
// call this function when you want to check the value
// returns true if value match, false otherwise
function checkSelectValue() {
return $('#yourselect').val() === initialSelectValue;
}
});
PS. You should use selected="selected" not selected="yes".
On page load, create an array with the initial value of each select box indexed by name:
var select_values = [];
$(document).ready(function() {
$("select").each(function() {
select_values[$(this).attr('name')] = $(this).val();
});
});
later when you need to check if a value has changed:
function has_select_changed(name) {
return $("select[name="+name+"]").val() != select_values[name];
}
First, a snippet:
$('select').each(
function(){
if( this.options[ this.selectedIndex ].getAttribute('selected') === null ){
alert( this.name +' has changed!')
}
});
Now the explanation:
Assuming selectElement is a reference to a <select /> elementYou can check which option is selected using
selectElement.selectedIndex
To get the <option /> element which is currently selected, use
selectElement.options[ selectElement.selectedIndex ]
Now when you know which option element is selected you can find out if this element has the selected='selected' attribute (as in the source code, it doesn't change - this is not the same as .selected propery of a DOM node, which is true for the currently selected option element and changes when the selection is changed)

Categories

Resources