JavaScript populating and clearing <input> textbox - javascript

I got 6 "textboxex" and an Array with them.
<input id="slot0" type="text" /> id from 0 to 5, also Array named "slotarray". I want arrray and textboxes to be bound slotarray[0] with input id="slot0" etc.
First i needed function that will find first empty field in array (no matter if corresponding textbox is empty - but should) and put there string (short string - shortcode like "abc" or "sp1").
This function also need to populate bound textbox with long string.
If slotarray[2] == 'abc' then with the same number in ID (here be id="slot2") need to contain long string like "Abrasive Brilliant Conexant".
Here what i got
click to populate
and then function
function populate(shortstring,longstring) {
for (var i=0; i<6; i++) {
if (slotarray[i] == '') {
slotarray[i] = shortsrting;
slotid = 'slot' + i;
document.getElementById(slotid).value = longstring;
break;
}
}
}
With clearing at the moment of creating: ( Array('','','','','','') ), and textbox .value=''; its working as it should.
But then i figured out that i need function to clear textbox and bound array field. Not all but one specific for one clic. So instead of 6 functions i start to wrote
clear this field
for each of textbox, with different numbers and ids ofcourse, and clearing function:
function clear(arrayid, slotid) {
slotarray[arrayid] = '';
document.getElementById(slotid).value = '';
}
But this function do not clearing textbox neither array. I see that textbox has text, and i know that array isn't cleared because first function works finding first empty object...
What am i doing wrong here? its definition of "empty"/"cleared" filed/textbox? maybe i need to use more complex conditions? maybe it is something else.
Maybe i don't need array (i can manage to get rid of short-codes) and just make functions work only on textboxes?
Ok - i prepared jsfiddle demo with this, but even populating don't work..
http://jsfiddle.net/BYt49/11/

You can't use the keyword clear because refers to the (deprecated) function document.clear; so try to change the name of your "clear" function.

Ok, whatever you have written is fine. Just change to way you call your javascript.
Here is jsfiddle: http://jsfiddle.net/BYt49/20/

Related

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

Javascript passing elementid in variable

I need to pass a variable to a javascript function which will then perform calculations and return the answer to another edit box on a form. I need to pass as I have 10 lines of edit boxes and dont want to have 10 seperate javascript functions.
function calc_totalcost(line)
{
$line_qty=line+"_qty";
$line_totcost=line+"_totcost";
$line_unitcost=line+"_unitcost";
$totcost=$line_qty.value*$line_unitcost.value;
document.getElementById('$line_totcost').value = $totcost;
}
on the html:
onchange="calc_totalcost('L1')"
So, on editbox 1 for L1_edit1 I need to send L1 to the function, which will then convert to 'L1_qty' which is an editbox (input) name where it will perform calculations using its contents. Hope that makes sense?
Thanks
You have a few issues, including the last line in the function which does not need the document.getElementById whereas all the others do need it.
function calc_totalcost(line) {
var $line_qty = document.getElementById(line+"_qty");
var $line_totcost = document.getElementById(line+"_totcost");
var $line_unitcost= document.getElementById(line+"_unitcost");
var $totcost=$line_qty.value*$line_unitcost.value;
$line_totcost.value = $totcost;
}

About a loop that creates dynamic buttons, but cannot give proper values [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript infamous Loop problem?
I am having a small issue, and it would be very nice if some of you could realize about what kind of logic is missing here, since I cannot seem to find it:
I have an array with the results of some previous operation. Let's say that the array is:
var results = [0, 1];
And then I have a bunch of code where I create some buttons, and inside a for loop I assign a different function to those buttons, depending on the position of the array. The problem is that for some reason, all the buttons created (two in this case) come out with the function assigned to the last value of the array (in this case, both would come out as one, instead of the first with 0 and the second with 1)
This is the code:
for (var i = 0; i < results.length; i++) {
var br2 = b.document.createElement("br");
var reslabel = b.document.createTextNode(Nom[results[i]].toString());
var card = document.createElement("input");
card.type = "button";
id = results[i]; // this is the problematic value.
card.onclick = newcard; // this function will use the above value.
card.value = "Show card";
divcontainer.appendChild(br2);
divcontainer.appendChild(reslabel);
divcontainer.appendChild(card);
}
As it is, this code produces as many buttons as elements in the array, each with its proper label (it retrieves labels from another array). Everything is totally fine. Then, I click the button. All the buttons should run the newcard function. That function needs the id variable, so in this case it should be:
First button: runs newcard using variable id with value 0
Second button: runs newcard using variable id with value 1
But both buttons run using id as 1... why is that?
It might be very simple, or maybe is just that in my timezone is pretty late already :-) Anyways, I would appreciate any comment. I am learning a lot around here...
Thanks!
Edit to add the definition of newcard:
function newcard() {
id = id;
var toerase = window.document.getElementById("oldcard");
toerase.innerHTML = "";
generate();
}
the function generate will generate some content using id. Nothing wrong with it, it generates the content fine, is just that id is always set to the last item in the array.
Your id is a global variable, and when the loop ends it is set to the last value on the array. When the event handler code runs and asks for the value of id, it will get that last value.
You need to create a closure to capture the current results[i] and pass it along (this is a very common pitfal, see Javascript infamous Loop problem?). Since newcard is very simple, and id is actually used in generate, you could modify generate to take the id as a parameter. Then you won't need newcard anymore, you can do this instead:
card.onclick = (function(id) {
return function() {
window.document.getElementById("oldcard").innerHTML = "";
generate(id);
};
}(results[i]));
What this does is define and immediately invoke a function that is passed the current results[i]. It returns another function, which will be your actual onclick handler. That function has access to the id parameter of the outer function (that's called a closure). On each iteration of the loop, a new closure will be created, trapping each separate id for its own use.
Before going on, a HUGE thank you to bfavaretto for explaining some scoping subtelties that totally escaped me. It seems that in addition to the problems you had, you were also suffering from scoping, which bit me while I was trying to craft an answer.
Anyway, here's an example that works. I'm using forEach, which may not be supported on some browsers. However it does get around some of the scoping nastiness that was giving you grief:
<html>
<body>
<script>
var results = [0,1];
results.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = "Show card";
document.body.appendChild(card);
});
function newcard(x) {
alert(x);
}
</script>
</body>
</html>
If you decide to stick with a traditional loop, please see bfavaretto's answer.

Cloned row requesting same function [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Call same function by a cloned list row
I am trying to make a simple calculation to work.
I have the following running:
http://jsfiddle.net/vSyK6/41/
Basically, the way it works now is this:
When you select an option on the drop down list it will display the content based on the option selected. Then when you select the same option again it will add, basically clone the same row.
Now, when the second option is selected "Option2" it will display an empty textbox. When you enter a number it will or should call the a function where we make a basic calculation. The function is already in the script.
However, when we have two empty textboxes it should call the same calculation function but calculate seperately and puts it in a different div. The div# where we display the amount is a called "amount"
Basically, it should work like this:
First Empty textbox -> 100 -> 100 * 22.38 = display result in div#1
Second Empty textbox -> 230 -> 230 * 22.38 = display in div#2
any idea on how to accomplish that ?
When cloning elements the id is cloned as well. It is best practice to create a new ID for the cloned elements, which will also help in accomplishing what you want. The same goes for the name attribute as well.
With a few modification to your code, http://jsfiddle.net/dNQVQ/3/, I was able to get what you were after. Let me first say that this might not be the ideal way to go, but it is a start. Like I said earlier the key is going to be setting unique ids for the cloned elements. What I did in this example was use a index as part of the list element id that is cloned with a matching index in an 'amount' div. This way when an input is updated the index is retrieved and then used to update the appropriate div. Additionally, I moved the function that did the calculation and updates to an anonymous function in the settimeout call. This makes it easy to use a reference to the updated input in the function call.
Joining the party quite late here :) Here is one vernon: http://jsfiddle.net/KVPwm/
ALso if its assignment bruv, put an assignment homework tag!
People around SO community are awesome folks so be truthful, guys will help man!
Use .on instead of live - recommendation. i.e. upgrade your JQ source if keen read this - What's wrong with the jQuery live method?
you have 2 document.ready functions also I chained few things for you.
Also think of using isNan check as well.
Rest you can read the code and play around a bit to make it more concise.
I have added 2 divs and using the id number to populate the stuff accordingly.
This should fit the cause :)
code
$("document").ready(function() {
/////////////////////////////////CALUCATIONS/////////////////////////////////
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 0; //time in ms, 5 second for example
$('input[name=Input2], input[name=Input1]').live('keyup', function() {
var str = $(this).prop("id");
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
amount = parseFloat($(this).val()) * 22.38;
typingTimer = setTimeout(doneTyping(matches), doneTypingInterval);
});
$('#Input2').keydown(function() {
clearTimeout(typingTimer);
});
function doneTyping(matches) {
$('#amount'+matches).text(amount.toFixed(2) + " lbs");
}
$("#List-Option1,#List-Option2").hide();
$('#category').change(function() {
var str = $('#category').val();
if (str == 'Option1') {
var option1 = $("#List-Option1:first").clone().show();
$('#box li:last').after(option1);
}
if (str == 'Option2') {
var option2 = $("#List-Option2:first").clone().show();
$('#box li:last').after(option2);
}
});
});​

getting selected values from an array of select box in to javascript

I have created dynamic select box using jquery. I have created the select box as an array name=Child[]. See my code
for(i=1;i<=val;i++){
var newParagraph = $('<dl class="thirty fl"><dt>Child '+i+'</dt> <dd><select name="child[]"><option value="">--select--</option><option value="1">1</option><option value="2">2</option><option value="3">3</option</select></dd></dl>');
$('#childDynamic').append(newParagraph);
}
In form validation section (in javascript), how I validate this select box? I don't know how to get the values from an array of select box using JavaScript
Anyone can help me?
Thanks in advance
(You don't actually have an array of select elements, given that html doesn't have arrays. But anyway...)
If you use the name attribute as the selector you can get a jQuery object containing the select elements:
$('#childDynamic select[name="child\\[\\]"]')
...which you can then process as you see fit.
Because square brackets have special meaning in jQuery selectors they need to be escaped with backslashes, and to include backslashes in a string literal they need to be escaped too.
Anyway, I don't know what kind of validation you want to apply, but if you wanted to loop through each select and check its value in some way you could do something like this:
var valid = true;
$('#childDynamic select[name="child\\[\\]"]').each(function() {
var val = $(this).val();
// example validation: make sure something other than the default
// blank value is selected
if (val === "") {
valid = false;
}
});
if (!valid) {
// do something
}

Categories

Resources