jquery get all input from specific form - javascript

Is there any ways to populate all of the input from certain form?
let say, some thing like this:
<form id="unique00">
<input type="text" name="whatever" id="whatever" value="whatever" />
<div>
<input type="checkbox" name="whatever" id="whatever" value="whatever" />
</div>
<table><tr><td>
<input type="hidden" name="whatever" id="whatever" value="whatever" />
<input type="submit" value="qweqsac" />
</td></tr></table>
</form>
<form id="unique01">
<div>
<input type="text" name="whatever" id="whatever" value="whatever" />
<input type="checkbox" name="whatever" id="whatever" value="whatever" />
</div>
<table><tr><td>
<input type="hidden" name="whatever" id="whatever" value="whatever" />
</td></tr></table>
<select>blah...</select>
<input type="submit" value="qweqsac" />
</form>
etc forms... forms...
*note: each form might have a different amount of input and type and also different html structure
so is there any way to populate the input from certain form id? eg if i click submit button from certain form id, then jquery will populate for me all of the input within those form id.
currently what i'm doing is like this:
$("form").submit(function(){ return validateForm($(this)) });
function validateForm(form){
var retVal = true;
var re;
$.each(form.serializeArray(), function(i, field) {
var input = $('input[name='+field.name+']');
field.value = $.trim(field.value);
switch(field.name){
case "name" :
and another cases...
}
})
}
that was work,
but in that case, i only get the field.name and field.value, and actually what i want is, i want a jquery object for each input element, so i can access their css, id, name, and even animate those input element
is there any way for this?
please let me know and thank you in advance!
AnD

To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.

The below code helps to get the details of elements from the specific form with the form id,
$('#formId input, #formId select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements from all the forms which are place in the loading page,
$('form input, form select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,
$('input, select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
NOTE: We add the more element tag name what we need in the object list like as below,
Example: to get name of attribute "textarea",
$('input, select, textarea').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);

Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.

$(document).on("submit","form",function(e){
//e.preventDefault();
$form = $(this);
$i = 0;
$("form input[required],form select[required]").each(function(){
if ($(this).val().trim() == ''){
$(this).css('border-color', 'red');
$i++;
}else{
$(this).css('border-color', '');
}
})
if($i != 0) e.preventDefault();
});
$(document).on("change","input[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
$(document).on("change","select[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});

Related

how to remove the emails while uncheck the checkbox from text area using javascript , there are multiple emails generated dynamically

how to remove the emails while unchecking the checkbox from text area, there are multiple emails generated dynamically i can remove all the emails while unchecking the checkbox except the first one...
here is my code
contactsCheckbox is id of checkboxes
showList is id of teenter code herextarea
var email = "";
$(document).on('change', "#contactsCheckbox", function () {
email = "";
if (this.checked) {
email = $(this).val().trim() + ";";
$("#showList").val($("#showList").val() + email);
}
else {
email = this.value;
var strValAdded = $("#showList").val().toString();
var rrr = strValAdded.indexOf(email.trim() + ";");
if (strValAdded.indexOf(email.trim() + ";"))
strValAdded = strValAdded.replace(email.trim() + ";", "");
if (strValAdded.indexOf(email.trim()))
strValAdded = strValAdded.replace(email.trim(), "");
$("#showList").val(strValAdded);
}
});
stringbuilder.Append("<div class=\"checkbox\">");
stringbuilder.Append("<label><input type =\"checkbox\" id=\"contactsCheckbox\" class=\"chk\" value=\"" + data.Email + "\">" + data.Email + "</label>");
stringbuilder.Append("</div>");
So first, element IDs are supposed to be unique. It is not your issue but it is very bad practice and you should correct that anyway. It will cause you more headaches down the road if you do not learn that now.
Your real issue is that your "if" statements are triggering false when you get to a value with a zero index. It is interpreting the zero index as a boolean value check:
Change:
if (strValAdded.indexOf(email.trim() + ";"))
to
if (strValAdded.indexOf(email.trim() + ";") > -1)
Example attached and I put an alert cmd in there so you can more visibly see what is happening with the 0 index boolean check. I also changed your change trigger to look by class instead of ID because your are going to fix your html to no longer be invalid in the near future...hopefully.
$(document).on('change', ".chk", function () {
if (this.checked) {
email = $(this).val().trim() + ";";
$("#showList").val($("#showList").val() + email);
}
else {
email = this.value;
var strValAdded = $("#showList").val().toString();
var rrr = strValAdded.indexOf(email.trim() + ";");
alert(Boolean(strValAdded.indexOf(email.trim() + ";")));
if (strValAdded.indexOf(email.trim() + ";") > -1) {
strValAdded = strValAdded.replace(email.trim() + ";", "");
}
if (strValAdded.indexOf(email.trim()) > -1){
strValAdded = strValAdded.replace(email.trim(), "");
}
$("#showList").val(strValAdded);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label><input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever1#wherwever.com"> whatever1#wherwever.com</label>
</div>
<div class="checkbox">
<label><input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever2#wherwever.com"> whatever2#wherwever.com</label>
</div>
<div class="checkbox">
<label><input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever3#wherwever.com"> whatever3#wherwever.com</label>
</div>
<input type="text" name="lname" style="width: 100%" id="showList" disabled >

How to count dynamically added inputs?

I have a simple form with two text boxes: One for peoples "name" and the other for their "surname". On the page you can click and it will add two more text boxes below, also for "name" and "surname".. so basically you could add as many pairs of name and surname as you want.
How do I count how many pairs/rows (of "names" and "surnames") of inputs?
You can see the demo here: http://poostudios.com/jstest2.html
Here's the code:
<html>
<head>
<script type="text/javascript" src="nutrition/jquery-3.1.1.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>enter code here
</head>
<body>
<form action="results.php" method="get">
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Name : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ><label> Surname : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Name : </label><input type='textbox' id='textbox1' >
<label>Surname : </label> <input type='textbox' id='textbox2' >
</div>
</div>
<input type='button' value='Add' id='addButton'>
<input type='button' value='Remove' id='removeButton'>
<input type="submit" value="Go">
</form>
</body>
</html>
There are dozens of ways to do this. #Tibrogargan and I have littered the comments on your question with various snippets which will return the number of elements at any given time.
However, each time you want to check the count, you'd need to call those methods in full to get a 'live' count — so if you're just planning to check the number of inputs once, i.e. when the form is submitted, for example, all you need do is, in your submit handler, check the count or store the count in a variable:
$('form').on('submit',function(e){
e.preventDefault();
// store the current count in a variable (this will not change if the user adds another input)
var current_count = $('#TextBoxesGroup input').length / 2;
// do what you want with the current_count variable
console.log("The user has submitted the form with " + current_count + " input fields");
});
However, perhaps you're not only planning to count the number of input fields once. Perhaps you're monitoring the user's behaviour. In such a case, you could define a function to make things a bit less verbose.
Instead of using a counter which you increment/decrement, just define a counter function in the following way:
function counter(){
return $('#TextBoxesGroup input').length / 2;
/*
This could also be:
return document.getElementById('TextBoxesGroup').getElementsByTagName('input').length / 2;
*/
}
Now, whenever you need to check how many input pairs there are, just call counter() and the value will be returned. So, let's imagine you're checking the number of inputs when the user clicks something — your code might look like this:
$('body').on('click', 'input[type=button]', function(){
// conditionally pass the current count straight to a function which uses the data
if ( counter() > 0 ) processMyData( counter() );
// or, if you process the data here, then pass it on to another function
// store the current count
var current_count = counter();
// do nothing if there are no input fields
if ( current_count < 1 ) return;
// do what you want with the count now that you have it
myAnalytics.inputs.save( current_count );
// do something else with it
processMyData( current_count );
// etc.
});
Since you are using jquery already, this is how you are going to get the length. Divide by 2 since each you have a set of name and username.
<script>
var len = $('#TextBoxesGroup').find('input').length / 2;
// Do whatever you wanted to do with the len
</script>
Here is the plunker sample
Firstly in your code, the ids are not unique so I modified it a bit just see the demo below ( I used the append() function for your markup creation ).
Secondly since you used a counter variable just use it to count the number of pairs by dividing it with 2 (counter / 2).
var counter = 2;
$("#addButton").click(function() {
$('<div>', {
id : 'TextBoxDiv' + counter
}).append(
$('<label>', {
text: 'Name : '
}),
$('<input>', {
type: 'text',
name: 'textbox' + (++counter), // increment counter for name
id: 'textbox' + counter,
value: ''
}),
$('<label>', {
text: 'Surname : '
}),
$('<input>', {
type: 'text',
name: 'textbox' + (++counter), // increment counter for surname
id: 'textbox' + counter,
value: ''
})
).appendTo('#TextBoxesGroup');
// just divide the counter by 2 to get the pairs
console.log('input text pairs: ' + counter/2);
});
$("#removeButton").click(function() {
// if counter === 2 (initial) then remove nothing
if (counter === 2) {
return false;
}
// decrement counter by 2
// and remove the textbox container
counter-=2;
$("#TextBoxDiv" + counter).remove();
console.log('input text pairs: ' + counter/2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="results.php" method="get">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Name : </label>
<input type='textbox' id='textbox1'>
<label>Surname : </label>
<input type='textbox' id='textbox2'>
</div>
</div>
<input type='button' value='Add' id='addButton'>
<input type='button' value='Remove' id='removeButton'>
<input type="submit" value="Go">
</form>
$("#textbox1").length will give you the count of occurrences of name text field.

Jquery , Html Append value to textfield when Checkbox is checked

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?
You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>
Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});
Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

Without using a form, how can I check an input field is not empty before running function?

I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):
<div id="formBox">
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label> <input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
</div>
Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.
It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.
I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...
function changeText2(){
var userInput = document.getElementById('userInput').value;
$('#formBox input[type="text"]').on('change', function() {
var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
alert(linktest);
});
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
I tried to check the input box like this, but it didn't work:
if( $('#formBox input[type="text"]').val== "") {
alert('no info');
}
It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,
For Jquery:
if( $('#userInput').val() === "") {
alert('no info');
}
For javascript:
if(document.getElementById("userInput").value === "") {
alert('no info');
}

Form Hidden Field Substitution

I'm building a form using Expression Engine's Safecracker module.
One of the the required fields is the Title, which becomes the title of the EE channel entry.
What I'd like to do is set the Title field to be the combined first name and last name fields.
I started with this:
<form method="POST" action="#">
<input id="student_first_name" type="text" size="30" name="student_first_name">
<br>
<input id="student_last_name" type="text" size="30" name="student_last_name">
<br><br>
<input type="text" name="title" value=""/>
</form>
And then added this:
$(function() {
$('#student_first_name').keyup(function() {
var snamef = $(this);
});
$('#student_last_name').keyup(function() {
var snamel = $(this);
});
$("input[name='title']").val(snamel + " " + snamef);
return false;
});​
​I can't get it to work, though: http://jsfiddle.net/tylonius/CY5zJ/4/
Am I missing a step (or just totally doing it wrong?)?
Also, am I possibly working too hard and Safecracker already has this function built in; similar to its live UrlTitle(); function?
Any help is appreciated.
Thanks,
ty
If I understood right your question try this:
First set an id on your desired input element, like this :
<input type="text" name="title" id="student_title" value=""/>
And then :
$(function() {
changeFunction = function() {
$('#student_title').val($('#student_first_name').val() + ' ' + $("#student_last_name").val());
}
$('#student_first_name').keyup(changeFunction)
$('#student_last_name').keyup(changeFunction);
});
Better yet, avoid using javascript altogether and just use SafeCracker's dynamic_title parameter.
dynamic_title="[student_first_name] [student_last_name]"
user1236048 has the best solution for you but below is a working version of your code
$(function() {
var snamef;
var snamel;
$('#student_first_name').keyup(function() {
snamef = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
$('#student_last_name').keyup(function() {
snamel = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
return false;
});
and here is the working jsfiddle

Categories

Resources