jQuery get / set value of textbox value in a repeater - javascript

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);
}
});
});

Related

Jquery gets new value from dom

In my page I am trying to hold old value and when something gets wrong I need to get it back.
ex:
var $oldVal;
$(document).delegate('.edit','click',function(){
$oldVal = $(this).closest('tr').find('input');
});
$(document).delegate('.save','click',function(){
$.get('servlet',function(result){
if (result.result == "true"){
$newVal = $(this).closest('tr').find('input');
}else if ( result.result == "false" ) {
$newVal = $oldVal; //
}
});
});
When I try to get new val in $.each like this;
$.each($newVal,function(k,v){
value = $(v).val(); /// PROBLEM ( 1 )
});
It will never get the old value. It always gets the new one. I am trying to make an input box that will be same after user input is right but if it is wrong then it needs to get older value.
All you're saving is a jQuery wrapper around the DOM element. You're not making a copy of the value.
var oldVal;
$(document).on('click', '.edit', function(){
oldVal = $(this).closest('tr').find('input').val();
});
That way you save the actual value of the input, so that if it changes you can restore it.
Note that the .delegate() API has been obsolete for a long time.
The problem is that you are storing the input element, not the value of the input element. The value can change while the input element stays the same.
To store the value, you should do this:
oldVal = $(this).closest('tr').find('input').val();
//...
if (!result.result) {
$(this).closest('tr').find('input').val(oldVal);
}

Checking if input value isn't empty working as wanted

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/

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

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