getting selected values from an array of select box in to javascript - 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
}

Related

AppleScript - If document.getElementById value is null, enter value

First time asking a question, let me know if I'm doing this wrong. I have an AppleScript that takes values from a Numbers document, and enters them into various fields of a webform using document.getElementById.
It works flawlessly, but now I want to add a feature so that it will only fill in a value if that field in the webform is blank.
My idea for the code was going to be something like this:
if ("document.getElementById('something').value = null)
execute javascript ("document.getElementById('something').value = '" & valueToFillIn & "'")
else
move on
Can someone advise me on the best way to check if a document.getElementById value is null, and then how to proceed? Very much appreciated!
Heres a very simple alternative as well. Modify for your needs. I believe its well explained and obvious of what is going on in the script. The else statement is not required to "move on". Once the if statement is checked, the script moves on without needing the else unless you want to execute something else if that field has value.
-- Tested Here -> http://meyerweb.com/eric/tools/dencoder/
set fieldValue to getInputById("dencoder") of me
if fieldValue is "" then
inputByID("dencoder", "Im Allowed to Input Text Because You Were Empty") of me
else
say "The Field Was Not Empty"
end if
-- Simple Handlers
-- Retrieve Value of elementById
to getInputById(theId)
tell application "Safari"
set output to do JavaScript "document.getElementById('" & theId & "').value;" in document 1
end tell
return output
end getInputById
-- Input My String to element by Id
to inputByID(theId, theValue)
tell application "Safari"
do JavaScript " document.getElementById('" & theId & "').value ='" & theValue & "';" in document 1
end tell
end inputByID
A few things you have to consider before use this snippet:
1- When this code will be triggered? Regularly in the click eventListener, like the example below:
2- Which value do you want to post? Please be more specific.
document.getElementById("myButton").addEventListener("click", checkInputs);
function checkInputs() {
if (document.getElementById("01").value == ""){
var newValue = document.getElementById("02").value;
document.getElementById("demo").innerHTML=newValue;
}
}
https://jsfiddle.net/azwt542p/2/
There are a few methods to get input textbox value straight (without wrapping the input element inside a form element):
These methods returns a collection of elements, so use [whole_number]
to get the desired occurrence, for first element use [0] and for
second one use 1 and so on...
Alternative 1:
Use document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollection
Eg. document.getElementsByClassName("searchField")[0].value;if this is
the first textbox in your page.
Alternative 2:
Use document.getElementsByTagName('tag_name')[whole_number].value
which also returns a live HTMLCollection
Eg. document.getElementsByTagName("input")[0].value; ,if this is the
first textbox in your page.
Alternative 3:
Use powerful document.querySelector('selector').value which uses CSS
selector to select element
Eg. document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name

jQuery :not() Selector doesn't work

I want to exclude selects with empty values from serialization.
I'm trying to achieve this like so:
var form = $('#myForm');
var str = $(':not(select[value=""])', form).serialize();
No erros, and the result is the entire form. The not() method gives the same.
What is possibly wrong?
EDIT: The question which was listed as possible duplicate to mine asks about possible implemntations for exlcuding empty fields frm serialization, while mine states that not() Selector doesn't work, asks why and for different to above mentioned solution.
Which filters element with element attribute value which equals to an empty string and not the element with current value as an empty string.
For filtering element with current value as empty string use filter() method.
var str = $(':input', form).filter(function(){
return this.value.trim() != '';
}).serialize();
UPDATE : If you just want to avoid empty select tags then do it like.
var str = $(':input', form).filter(function(){
return !($(this).is('select') && this.value.trim() == '');
}).serialize();

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

JS: Form validation on input type

I'm trying to do some form validation, however don't want to to select form input by class name. Is there a way I can loop through the validation based on input attribute type. I've had a play with the code, but to little avail. Potentially thinking something along these lines:
EDIT: I don't want to use a plugin
function validator (myForm) {
// If type equals Email
if($(myForm + " input").attr("type") == "email") {
// Validate Email Here
}
// If type equal text
if($(myForm + " input").attr("type") == "text") {
// Validate Text Here
}
}
Yes, you can do something like that.
First, if myForm is a DOM element, then you'll want $(myForm).find(...) rather than $(myForm + " ..."), because the latter will result in an invalid selector. If myForm is a string containing a valid selector, it's fine.
Your if($(myForm + " input").attr("type") == "email") { won't work because what that will do is get the type of the first input in your form and compare it to the string "email". It won't find all the email inputs in your form.
You can select specific types of inputs using an attribute selector, e.g.:
$(myForm).find("input[type=email]").each(function() {
// Validate email inputs; each input is available as `this`,
// which is a DOM element
});
and
$(myForm).find("input[type=text]").each(function() {
// Validate text inputs; each input is available as `this`,
// which is a DOM element
});
(In this case, we don't need quotes around the attribute values because they're single words.)
You might also look into the HTML5 form validation stuff.
And of course, you probably know this, but any validation you do with client-side JavaScript (or other browser features) is purely for UI/UX purposes. You still have to validate things on the server, as client-side validation can be completely bypassed...
you can find input element by attribute like below.
//If type equals Email
$('input [type = email]')
// If type equals Email
$('input [type = text]')
like above you can access.

JavaScript populating and clearing <input> textbox

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/

Categories

Resources