How to get siblings in different DIVs or SPANs? - javascript

I have a number of forms on a page, like this:
<form>
<input type="hidden" name="id" value="someID1">
<div>
<span>
<input type="submit" class="submitClass">
</span>
</div>
<div>
<input type="text" name="name" class="someClass" value="name1">
</div>
</form>
<form>
<input type="hidden" name="id" value="someID1">
<div>
<span>
<input type="submit" class="submitClass">
</span>
</div>
<div>
<input type="text" name="name" class="someClass" value="name1">
</div>
</form>
Then I have some JS:
jQuery(document).ready(
function()
{
console.log("page loaded");
jQuery(".submitClass").on("click", function() {
var id = jQuery(this).siblings("input[name='id']").val();
var name = jQuery(this).siblings("input[name='name']").val();
console.log(id);
console.log(name);
return false;
});
}
);
JSFIDDLE: http://jsfiddle.net/sEXg3/
When the submit button is clicked, I want to stop the form from being submitted and get the values of the two inputs I have next to the submit button.
I tried doing this with the .siblings() function, but it doesn't work since the inputs are in different DIVs/SPANs (if I put them all right next to each other, it does work).
How can I accomplish this?

The elements you are looking for are not the sibling of the submit button.
In your case I would suggest to find the form element (you can find the form element in which the clicked button is present using .closest()) and them find the desired inputs fields inside it using .find()
jQuery(function ($) {
console.log("page loaded");
$(".submitClass").on("click", function () {
var $this = $(this),
$form = $this.closest('form');
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
console.log(id);
console.log(name);
return false;
});
});
Demo: Fiddle

Since your .submitClass is placed in div and in span it's not a sibling of the other inputs... you can try something like this: (Working jsFiddle)
var id = jQuery(this).closest('form').find("input[name='id']").val();
var name = jQuery(this).closest('form').find("input[name='name']").val();
You first look for the parent form, then inside it look for the input fields.. an even more efficient version will be:
var $form = jQuery(this).closest('form');
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();

Related

Combine url with multiple same args from submitted form

I have a form with multiple checkboxes, all called filter. When the form gets submitted, they get added to the URL, "example.com/?filter=var", as expected.
When there are multiple checkboxes selected, they get added to the url like so: "example.com/?filter=var&filter=var2".
Is it possible to change this somehow? I need them in the url as "example.com/?filter=var+var2".
Is this possible to achieve somehow? Using Javascript is no problem.
Add a function call to your Submit button and leave your form tag like this <form>.
$(function () {
$('#target').click(function () {
var checkValues = $('input[name=checkboxlist]:checked').map(function() {
return $(this).parent().text();
}).get().join('+');
window.location.href = "http://example.com/?filter="+checkValues;
});
});​
You can use a hidden field for that, and in the submit event you set it's value with the filters. The hidden will get the name as filter and the checkboxes' values will be ignored:
//$("form").on("submit", function() {
$('input[type="submit"]').on("click", function() {
var filter = [];
$('input[type="checkbox"]:checked').each(function() {
filter.push(this.value);
});
$("#filter").val(filter.join("+"));
console.log("filters", filter.join("+"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="hidden" name="filter" id="filter" />
<input type="checkbox" value="val1" />
<input type="checkbox" value="val2" />
<input type="checkbox" value="val3" />
<input type="submit" />
</form>
Use $("form").on("submit", function() { instead of the event in the button. I just commented it because you can't submit in StackOverflow snippet.
Fiddle Version

Run function after a checkbox change on my page

I have dynamically created check boxes on my page and assigned each of them an unique id like 'renameteam1', 'renameteam2' etc.. I am trying to run a function when one of these gets checked. The function will then allow the user to enter a corresponding field that was previously readonly.
I have tried the following but it doesn't seem to be working.
var a=0;
$('input[type=checkbox]').change(function () {
for (var i=0;i<rows3;i++){
a=a+1;
var id= '#renameteam'+a;
if ($(id).is(":checked")) {
$('#newname'+a).removeProp('readonly');
}
}
//Here do the stuff you want to do when 'unchecked'
});
Any Suggestions?
This is how I would do it
//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#' + checkbox.data('id'));
otherInput.prop('readonly', !checkbox.is(':checked'));
if (!checkbox.is(':checked')) {
// do stuff here when checkbox isn't checked - not sure if you still want this bit but it is as per your comments in the code above
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" data-id="newname1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />
If you don't want to use a data attribute, you could do this:
//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#newname' + this.id.replace('renameteam', ''));
otherInput.prop('readonly', !checkbox.is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />
Try using an on click instead of on change for checkboxes and radio buttons.

jquery - copy value of input from one form to another (form and input named the same)

I would like to copy the value from an input in one form to the value of an input(with the same name) of the next form down. The forms and inputs are named the same. All it needs to do is copy the value of the title input to the title input one form down.
<form>
<input name="file" value="1.xml">
<input name="title" id="title" value="Smith">
<input type="submit" id="copy-down" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title" value="Anderson">
<input type="submit" id="copy-down" value="copy">
</form>
etc...
In this case when the top "copy" button is clicked I would like jquery to overwrite Anderson with Smith.
$('#title').attr('value'));
Gives me Smith but I'm not sure what to do with that value once I have it.
Change HTML to this:
<form>
<input name="file" value="1.xml">
<input name="title" id="title1" value="Smith">
<input type="submit" id="copy-down1" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title2" value="Anderson">
<input type="submit" id="copy-down2" value="copy">
</form>
Javascript:
function copyHandler() {
var copyVal = document.getElementById("title1").value;
var replaceInput = document.getElementById("title2");
replaceInput.value = copyVal;
}
document.getElementById("copy-down1").onclick = function(){
copyHandler();
return false;
}
Some notes:
This is so straightforward in vanilla javascript that I didn't add the jQuery code.
You should never assign multiple elements to the same ID, class or name can be used for that purpose.
The return false; portion of the onclick function is necessary so that the form doesn't reload when you click your submit button.
Let me know if you have any questions.
you can try
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var GetNameAttr = $(this).find('input:nth-child(2)').attr('name');
var GetTitleValue = $(this).find('input:nth-child(2)').val();
var NextFormNameAttr = $(this).next('form').find('input:nth-child(2)').attr('name');
if(NextFormNameAttr == GetNameAttr){
$(this).next('form').find('input:nth-child(2)').val(GetTitleValue );
}
});
});
Note: this code will change the second input value in next form with
the second input value of form you click if the name is same .. you
can do the same thing with the first input by using :nth-child(1)
Demo here
if your forms dynamically generated use
$('body').on('submit','form', function(e){
instead of
$('form').on('submit', function(e){
for simple use I create a function for that
function changeNextValue(el , i){
var GetNameAttr1 = el.find('input:nth-child('+ i +')').attr('name');
var GetTitleValue1 = el.find('input:nth-child('+ i +')').val();
var NextFormNameAttr1 = el.next('form').find('input:nth-child('+ i +')').attr('name');
if(NextFormNameAttr1 == GetNameAttr1){
el.next('form').find('input:nth-child('+ i +')').val(GetTitleValue1);
}
}
use it like this
changeNextValue($(this) , nth-child of input 1 or 2);
// for first input
changeNextValue($(this) , 1);
// for second input
changeNextValue($(this) , 2);
Working Demo

Add form input to variable

I cannot find the accept answer on here.
Currently I have a simple html form, that allows the user to enter text, in this case a user name.
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" required/>
<button type="submit" class="btn btn-login">Find</button>
</form>
I want to capture that name in a variable for later use. Do I simply use ?
var findFriend = friendsearch;
To keep the var updating on each user input, you can use.
http://jsfiddle.net/gRZ7g/
var friendName;
$('#friendsearch').on('keyup', function(e) {
friendName = $(this).val();
});
$('.show-value').click(function(e) {
alert(friendName);
});
You can get it like this:
var findFriend = $('#friendsearch').val();
You have to use the jQuery selector to select the element by its id.

Get input value into a <form> inline

Following my code:
<script>
function getText(text){
alert(text);
}
</script>
<form action="getText(/*here function for get text*/)">
<input type="text" class="text"/>
<input type="submit"/>
<div></div>
</form>
How to get textarea value with pure javascript in the <form> where indicated?
The action attribute contains the URL that the form will be submitted to, not JavaScript.
If you want to process the form data with JavaScript, then bind a submit event handler to it. This will be fired in the context of the form, so you can access the form element via this.
You can access the form controls through the elements collection. They will have value properties containing their values.
<form action="/some/handler" id="myForm">
<textarea name="myTextArea" class="text"></textarea>
<input type="submit">
<div></div>
</form>
<script>
function getText(text){
alert(text);
}
function formSubmitHandler(evt) {
var textarea = this.elements.myTextArea;
getText(textarea.value);
}
document.getElementById('myForm').addEventListener('submit', formSubmitHandler);
</script>
You may wish to call evt.preventDefault() if you are going to handle the form processing entirely with JS (when JS is available).
If you want value from input without using selector, then you can use some thing like this,
but remember, the value your are getting from input tag should be used as a first child of form element.
<form action="">
<input type="text" class="text"/>
<input type="button" onclick="getText()" value="get value">
<div></div>
</form>
<script>
function getText(text){
var textValue = document.getElementsByTagName('input')[0].value;
alert(textValue);
}
</script>
EDIT
If you want the text from input value after pressed the enter key then you could do like this.
<form action="">
<input type="text" class="text" onkeydown="getText(event)"/>
<div></div>
</form>
<script>
function getText(event){
var textValue = document.getElementsByTagName('input')[0].value;
if(event.which == 13){
alert(textValue);
}
}
</script>
Here a little function for you
function getTextAreaByClass(lookFor) {
var i; /* I always define at the top so jslint doesn't carp */
var elems = document.getElementsByTagName("textarea");
for (i in elems) {
if((' '+elems[i].className+' ').indexOf(' '+lookFor+' ') > -1) {
return elems[i].innerHTML;
}
}
return ""; /* or return false or whatever else you want to denote not found */
}
The above will search through all the textarea tags, look for a class that matches and will return the content within the textarea.

Categories