I found this online:
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var the_default = $(this).val();
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
As you can see, it grabs the text within a value attribute and sets it as the default_value. It then checks the current_value against the default.
I'm running into a problem.
In this example, we have an element like:
<input type="text" class="placeholder" value="potato">
If the user focuses and unfocuses the input, it works great - removing and repopulating with "potato".
However, let's say a user enters "ioqiweoiqwe", and then unfocuses the input (fills out the rest of the form"). They then go back to our input and delete all of their text, and click on another field. The input would be re-populated with "ioqiweoiqwe" - when really, we want it to be re-populated with the default_value. How do I manage to do this?
Yours sincerely,
a jQuery nub.
Note: I set up a jsfiddle here... a bit after some comments: http://jsfiddle.net/xmhCz/
I don't really know what the problem with that code is, but it looks like it was written by someone who didn't know much JavaScript. I rewrote the functionality:
$("input.placeholder").each(function() {
var me=$(this);
var defaultValue=me.val();
me.focus(function() {
if(me.val()===defaultValue) {
me.val("");
}
});
me.blur(function() {
if(me.val()==="") {
me.val(defaultValue);
}
});
});
Test it out on JSFiddle.
HTML inputs have defaultValue
Related
Could someone please help me handle this issue in jQuery
I have a requirement where I have two dropdowns:
The no of floors of the flat (numberOfFloors)
The flat where the user stays (whichFloorYouStay)
I need to remove all the invalid options from the second dropdown. How do I achieve this?
For example:
If a user select the numberOfFloors option as 3, then I should remove options 4 and 5 from whichFloorYouStay dropdown and just load 1,2,3 as whichFloorYouStay options.
Similarly, if a user select the numberOfFloors option as 1, then I should remove options 2,3,4,5 from whichFloorYouStay dropdown and just load 1 as whichFloorYouStay option.
Please find my JSBin link:
http://jsbin.com/sibufive/1/edit?html,js,output
Try this:
$(document).ready(function () {
//NEW CODE:
var floorsvals = new Array();
var lastvalue = Number.MAX_VALUE; //Useful for checking whether we need to append or remove elements - Initialize this with an arbitrarily large number
//Fill possible floor vals with value of <option>'s
$("#numberOfFloors option").each(function () {
floorsvals.push($(this).val());
});
//NOTE: If you already know the values of the numberOfFloors array, you can just add those values straight into the "floorsvals" array
//The above loop is just handy if you are dynamically generating a <select> list and don't already know the values
$("#numberOfFloors").change(function () {
alert($("#numberOfFloors").val());
var value = $("#numberOfFloors").val();
//NEW CODE:
//If we need to append...
if (value > lastvalue) { //This value is larger than the last value we just had
for (i = 0; i < floorsvals.length; i++) {
if (floorsvals[i] <= value && $('#whichFloorYouStay option[value=' + floorsvals[i] + ']').length === 0) { //Floor value is less than the selected maxvalue and an option with this floor value doesn't already exist...
$('<option value="' + floorsvals[i] + '">' + floorsvals[i] + '</option>').appendTo("#whichFloorYouStay"); //...So add that floor value
}
}
} else { //Otherwise, we need to remove
//OLD CODE:
$('#whichFloorYouStay option').each(function () { //Go through each option
if ($(this).val() > value) { //If this option's value is greater than the numberOfFloors value, remove it
$(this).remove();
}
});
}
//NEW CODE:
lastvalue = value; //Update last value chosen with this value
});
});
Here's a demo: http://jsbin.com/sibufive/40/edit
var value = $("#numberOfFloors").val();
should become
var value = $("#numberOfFloors").val();
value-=1
I would also suggest adding a value 0 to the first set of options one so you never have a user begin at 1 and try to move to the second menu
I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});
I have a piece of code that creates check boxes in a table in a loop and calls their onclick function. In the onclick function, I try to populate a global array that will be a position holder for the checked check boxes of the table. Also if a row is checked, I have to sum the numbers in a text field of that row(I add this to a variable percentage) and if the variable crosses 100 I have to alert the user and ask him to enter values in the checkbox such that the sum is less than 100.
My problem is that each time I click a check box, the global array gets populated, sum is stored in the variable as expected, but the 'tick' on the check box doesn't come/disappears immediately.
How do I solve this issue?
Code:
{
var tabId=document.getElementById("AmnestyTransTbl");
var tabrows = tabId.getElementsByTagName('tr');
var percentage=0,c,n;
var ar=[];
for(var i=1,c=2;i<=tabrows.length-3;i++,c=c+2)
{
// Create CheckBox
ar[i]=c;
var checkBox = document.createElement("input");
checkBox.setAttribute("type", "checkbox");
checkBox.id='CB'.concat(i);
checkBox.onclick = function ()
{
var tabId1=document.getElementById("AmnestyTransTbl");
var rowInd=getRowIndex(this);
CBValue[rowInd]=this.checked;
n=ar[rowInd-1];
percentage=(parseInt(percentage) + parseInt(tabId1.getElementsByTagName("input")[n].value));
if(parseInt(percentage)>100)
{
alert("Amnesty Percentage,"+percentage+", greater than 0!. Plesase check again.");
this.checked=false;
}
if(this.checked==false)
percentage=parseInt(percentage)-parseInt(tabId1.getElementsByTagName("input")[n].value);
} }
var td = document.createElement("td");
td.appendChild(checkBox);
tabrows[i+1].cells[1].appendChild(td);
}
function getRowIndex(el)
{
while((el=el.parentNode) && el.nodeName.toLowerCase() != 'tr');
if (el)
return el.rowIndex;
}
Got the culprit i guess,
Plz try replacing this
if(parseInt(percentage,10)>100) {
this.checked=false;
}
if(this.checked=false)
{
percentage=parseInt(percentage)-parseInt(tabId1.getElementsByTagName("input")[n].value);
}
with this
if(parseInt(percentage,10)>100) {
this.checked=false;
}
else
{
this.checked=true;
}
if(this.checked==false)
{
percentage=parseInt(percentage)-parseInt(tabId1.getElementsByTagName("input")[n].value);
}
Lets clarify my question,
I want to make an element which the element contains 5 fields so I dont want the user should be able to put in a new element if the old one is null, so I made the alert when looping through the old element and see if there is some strings, if not then dont put a new element and make an alert please fill out all fields
Here again my code
function addEvent() {
var ni = document.getElementById('discount'); // Takes the a div named discount
var discountForm = document.getElementById('discountForm'); // Takes the a form named discountForm
var numi = document.getElementById('theValue'); // Takes the a hidden input field named theValue
var num = (document.getElementById("theValue").value -1)+ 2; // Start counting to set the new divs form numbers
numi.value = num;
var divIdName = "my"+num+"Div"; // the new divs will be named
var allDivTags = discountForm.getElementsByTagName('div'); // take all div tags
var numOfDivs = (allDivTags.length -1); // take the number of the old div
var oldDivIdName = document.getElementById(allDivTags[numOfDivs].id); // old div id
var newdiv = document.createElement('div'); //the new div
newdiv.setAttribute("id",divIdName);
newdiv.innerHTML = "Company <select name=\"company[]\"><option value=\"\"></option><option value=\"ZI\">Avis</option><option value=\"ET\">Enterprise</option><option value=\"ZE\">Hertz</option><option value=\"ZD\">Budget</option><option value=\"ZR\">National</option><option value=\"AL\">Alamo</option></select> Discount Type <select name=\"type[]\"><option value=\"CD\">Discount Number</option><option value=\"PC\">Coupon Number</option></select> Code <input name=\"code[]\" type=\"text\"> Title <input name=\"title[]\" type=\"text\"> Remove"; // creating the fileds in the new div
ni.appendChild(newdiv);
for(i=0; i<discountForm.elements.length;i++){ // loop through the divs
if(numOfDivs != i-1){ // if tho old div exist and if the old div fields are empty
if(oldDivIdName.children[i].value.length == 0){
removeElement(divIdName); // then dont put the new one
alert('Please enter all fields');
}
}
}
}
But my problem is that in IE comes out an error children[...].value.length is null or not an object so I trying to figure how to fix it,
I hope its more clearly for you now.
It's very hard to tell from the information you've given us. But my first guess is the following:
for(i=0; i<discountForm.elements.length;i++){
if(numOfDivs != i-1){
if(oldDivIdName.children[i].value.length == 0){
removeElement(divIdName);
alert('Please enter all fields');
}
}
}
Above you're doing:
oldDivIdName.children[i]
But i is defined as the number of elements in the form from what I can see... not the number of children of the oldDivIdName. If there are more elements in the form than there are in oldDivIdName then the value of oldDivIdName.children[i] will be null. And "value" is not defined on null.
It's very hard to tell from the information you've given us. But my first guess is the following:
When you first call this method, allDivTags.length whether is null or negative, and results
not got element:
var oldDivIdName = document.getElementById(allDivTags[numOfDivs].id);
I have an .aspx hidden control that stores a defaultId for this dropdown. However, the values in the dropdown can change and sometime the defaultId is listed as one of the selections, other times it isn't. When the drop down clears we run this to reset it:
Global.getComponent("ddlVehicleType").setValue(Global.getComponent("DefaultVehicleTypeId").getValue());
Now when it sets that, if the dropdown doesn't have a value associated with that Id, it displays the actual Id in the field. I have a check for isNumeric now to see when that happens, but how do I make the field display the first value in the list of Id's it DOES have:
var displayedValue = Global.getComponent("ddlVehicleType").getRawValue();
if (IsNumeric(displayedValue)) {
}
Put together a unique little way of doing it, by going through the current populated store of that dropdown on the page:
var newId = 0;
var firstId = 0;
var typeStore = Global.getComponent("ddlVehicleType").getStore();
firstId = typeStore.getAt(0).get('LookupID');
typeStore.each(function(rec) {
if (rec.get('LookupID') == Global.getComponent("DefaultVehicleTypeId").getValue())
{
newId = Global.getComponent("DefaultVehicleTypeId").getValue();
}
});
if (newId != 0) {
Global.getComponent("ddlVehicleType").setValue(newId);
} else {
Global.getComponent("ddlVehicleType").setValue(firstId);
}