Jquery get array of input element values within a common parent - javascript

I have a jquery application where I am templating an html block that contains 3 textfields. I need to get the values of the text fields within a specific block. the identifiers are replicated in all blocks.
Sample Code
<div>
<div class="htmlBlock">
<ul>
<li>
<input class="myInput1" type="text">
<input class="myInput2" type="text">
<input class="myInput3" type="text">
</li>
<li>
<input class="myInput1" type="text">
<input class="myInput2" type="text">
<input class="myInput3" type="text">
</li>
<li>
<input class="myInput1" type="text">
<input class="myInput2" type="text">
<input class="myInput3" type="text">
</li>
</ul>
<button class="clickMe">Click to get values of this block</button>
</div>
<div class="htmlBlock">
<ul>
<li>
<input class="myInput1" type="text">
<input class="myInput2" type="text">
<input class="myInput3" type="text">
</li>
</ul>
<button class="clickMe">Click to get values of this block</button>
</div>
</div>
When I click the .clickMe button I want to call $('.myInput').val() and get the value only within the block that the button is located.

$('button.clickMe').on('click', function() {
var values = $(this).closest('.htmlBlock').find('input[type="text"]').map(function(){
return this.value;
}).get();
});

You can do the following:
$('button.clickMe').on('click', function() {
var block = $(this).closest('.htmlBlock');
var inputs = block.find('input[type="text"]');
// .myInput1 values as an array.
var myInput1Vals = block.find('.myInput1').map(function() {
return this.value;
});
// Do what you want to do
});
I didn't use $('.myInput').val(), since you have different classes on each input. But you can loop through them, do whatever you want with them and they will all be localized within that block.
jsfiddle
This fiddle converts it to an array that is not a jQuery object using .toArray() after the .map.

Related

Find the nearest id in javascript

I have two divs
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(nearest input type hidden)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(nearest input type hidden)">Remove</div>
</div>
I want to send as a parameter the value of nearest input type hidden of that div that we are clicking on
Im not 100% sure what you mean with nearest but with this you get the input hidden inside the div. By the way you could also put the element.parentNode.querySelector into the onclick but personally i like it more to split HTML and JS.
function removeInput(element){
let value = element.parentNode.querySelector("input[type='hidden']").value;
console.log(value);
}
<div class="maca">
<input type="hidden" value="1">
<div onclick="removeInput(this)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="5">
<div onclick="removeInput(this)">Remove</div>
</div>
You can send the event as a parameter to a javascript function and then find the input via the parentNode. This isn't a literal interpretation of your question since faithfully the "nearest" element is rather complex and probably not what you're looking for.
function removeInput(e) {
const nearestInput = e.target.parentNode.querySelector("input[type='hidden']");
console.log(nearestInput);
}
<div class="maca">
<input type="hidden" value="1" />
<div onclick="javascript:removeInput(event)">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1" />
<div onclick="javascript:removeInput(event)">Remove</div>
</div>
You should not use inline event listeners, which are widely considered bad practice.
Instead, use addEventListener to add the click listeners, and find the input (given your markup structure is fix like you've shown) using previousElementSibling:
for (const remover of document.querySelectorAll('.remove-input')) {
remover.addEventListener('click', () => remover.previousElementSibling.remove(), { once: true });
}
<div class="maca">
<input type="hidden" value="1" />
<div class="remove-input">Remove</div>
</div>
<div class="maca">
<input type="hidden" value="1" />
<div class="remove-input">Remove</div>
</div>

Bind onlick events on several links

I am currently working on a solution for an application that is written in PHP, but needs a JS solution for a preview link and I am stuck with binding onclick-events on the links. The HTML is given and may not be changed. (so no adding of classes and stuff, even though that would be easier)
My initial thought was to just get each of the li and perform a callable that sets the event and defines the rules for what happens, when the link is clicked.
I am unsure what is the best possible solution to get the values of the two Inputs, belonging to the preview link, as while I was running the code mentioned above on what ever link I clicked, the last item was logged.
So basically this is 2 questions in one:
1. how to properly bind the click events.
2. how to best acces the inputs belonging to the link
var items = $('div.foobar').find('li');
items.each(function() {
this = $(this);
url = lo_this.find('a').attr('href');
this.find('a').click(function(event) {
event.preventDefault();
console.log(this)
/** here is the point, where I got stuck **/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>
You mean this?
Assuming your inputs are in the same LI as the anchor
Ignoring the ID of the anchor and just getting the inputs in the same LI
Other code is needed if you want to use the ID of the link to access the named links
$('div.foobar li a').on("click",function(e) {
e.preventDefault();
$(this).closest("li").find("input").each(function() {
console.log(this.name,this.value)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[ID][foo]" value="">
<input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
</div>
</li>
<li>
Link
<div class="justaname">
<input type="text" name="somenamewith[OTHERID][foo]" value="">
<input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
</div>
</li>
</div>
You can do this to bind click events to your links and then do whatever with the input elements contained by the div after the clicked link:
$('.foobar li a').on('click',function(event){
event.preventDefault();
$(this).next().find('input').each(function(){
//Whatever you want to do for each input
});
});

How can I get HTML element value by JavaScript?

<div class="gallery_re_form">
<form action="http://gall.dcinside.com/?/forms/comment_submit" method="post" accept-charset="utf-8" name="comment_write" id="comment_write" />
<div style="display:none">
<input type="hidden" name="ci_t" value="625752bb366f010c56e506e5d0f93822" />
</div>
<input type="hidden" name="ehqo_C" id="ehqo_C" value="spam_key" />
<input type="hidden" name="spam_key" id="spam_key" value="rhkdrhgkwlak!!" />
<input type="hidden" name="fb8f95190d2b70480acb309f91653d7e4416d4f99a0b67a0b866f06087fdec4588f68fe210675e74919d2ecc50e08f1fd6f75119" id="fb8f95190d2b70480acb309f91653d7e4416d4f99a0b67a0b866f06087fdec4588f68fe210675e74919d2ecc50e08f1fd6f75119" value="b9d3cc45576e30144d8f299fdc61356552989b3aba08238c811b1d3183a104cc2d1d3984af72c4f2eaa2738ca41819d05533731a" />
<input type="hidden" name="service_code" value="21ac6e96ad152e8f15a05b7350a24759b5606fa191c17e042e4d0175735f4c61d63153c3ce7b4eb89b565a7f6a04ad0667df75f39625ab6fe0816d23f4bed5387546b52d6874b5c201e54df7b5db9187219b048cffc9ef8a106febabfba125eff122df732d9cc52fcaae8b11c42ff5f6fd5ef81901df4103827e7233615992141c180be76852634d53b60c6f911ccdfc762b3db554d8ee36528547bceede30697120c5291acb255a" />
<br />
<div class="re_input">
<div>
<ul>
<li>
<input type="text" name="name" id="name" class="re_name re_in" onfocus="this.style.background='#FFFFFF'" title="nickname" />
</li>
<li>
<input type="password" name="password" id="password" class="re_pw re_in" onfocus="this.style.background='#FFFFFF'" title="password" />
</li>
</ul>
</div>
</div>
</form>
I'm trying to rewrite google chrome extensions. I want to get #spam_key s #service_codes value in this HTML response.
I have not used JavaScript.
How can I get HTML element id (spam_key, service_code) and value by JavaScript?
DOM has a document object , you can use it like this to get the HTML element what you want
document.getElementById("id")
Now to get value, just use value property of this element.
document.getElementById("id").value
You want to retrieve the spam_key element and service_code element's values?
var spam_key = document.querySelector('#spam_key');
var service_code = document.querySelector('input[name=service_code]');
console.log(spam_key.value);
console.log(service_code.value);
You can learn more about selection element from javascript at here
You can get value of an HTML input element using:
var spam_key = document.getElementById('spam_key').value;
var service_code = document.getElementById('service_code').value;
Try this, It should give the value of spam_key
document.getElementById('spam_key').value;
If you have jQuery included you can get it by following: $("#spam_key").val()

Getting label text of checkbox and appending to div

Working on revamping some old code and needing some help on this last addition. Basically can have a variable number of checkboxes and need to get the labels text to any of those checkboxes and append that text to another div. Have rewritten this a ton of times and used a lot of others code but nothing seems to be working. Have seen several similar questions on here but none of those have worked for a solution to this problem.
Problem:
Get a labels text associated to it's input checkbox. Then once that text value is gathered append it to a separate div.
Note:
The checkboxes have an ID and a VALUE that are the same because of some different code versions just trying to get them to work. Would like a solution using VALUE only.
HTML:
<a cid="38" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="38" id="38">
<label for="38">Category ONE</label>
</div>
</a>
<a cid="14" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="14" id="14">
<label for="14">Category TWO</label>
</div>
</a>
<div id="labelName"></div>
JS:
$(".cat_filter").live('click', function() {
$(this).find("input:checkbox").attr("checked", true);
var labelName = $(this).find("label[for='"+$(this).attr("id")+"']").text();
labelName.appendTo('#labelName');
});
Fiddle:
http://jsfiddle.net/wfuller/o25z9w0f/1/
Any help would be greatly appreciated.
So this should solve your problem:
$(".cat_filter").on('click','input',function() {
//On click on an input field. if this isn't OK tell me and I will change it again.
$('#labelName').html($('label[for='+$(this).prop('id')+']').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a cid="38" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="38" id="38">
<label for="38">Category ONE</label>
</div>
</a>
<a cid="14" href="javascript:void(0);" class="cat_filter">
<div class="cat-filter_checkbox">
<input class="cat_filter_checkbox" name="" type="checkbox" value="14" id="14">
<label for="14">Category TWO</label>
</div>
</a>
<div id="labelName"></div>
Greetings from Vienna
var nodeList = document.querySelectorAll('input[type ="checkbox"]');
var div = document.getElementById('myDiv');
for (node in nodeList) {
div.innerHTML += node.text; //or label if you set that attribute on the element
}
Does not rely on jQuery

Multiple checkbox values search javascript

I have a list of keywords, and I've created a checkbox for each. My template has a form wrapping the content, so I can't have a nested form around the checkbox list.
How can I send the selected checkbox values to my search results page?
The form that wraps the content doesn't have any actions or methods applied:
<form id="BoostMasterForm" runat="server">
This is an example of the HTML markup of my checkbox list (the checkboxes will be different depending on the keywords):
<div class="checkboxes">
<ul>
<li>
<input type="checkbox" name="search" class="options" value="one">
<label>one</label>
</li>
<li>
<input type="checkbox" name="search" class="options" value="two">
<label>two</label>
</li>
<li>
<input type="checkbox" name="search" class="options" value="three">
<label>three</label>
</li>
</ul>
<input type="submit" value="Submit"/>
</div>
How can I use javascript or jQuery to submit the values of the multiple checkbox selections and on submit action them to the following URL: '/imagery/image-search.aspx'
The resulting URL for a search where option 1 and 3 are submitted should be: '/imagery/image-search.aspx?search=one%20three'
I'm using this javascript that I found on another post, however I need it to append the form an the action and the method. My website is ASP, where this post is for a PHP site:
Sending multiple checkbox options
$('.options').click(function() {
var selectedItems = new Array();
$(".checkboxes input:checkbox[name=search]:checked").each(function() {selectedItems.push($(this).val());});
var data = selectedItems.join('|');
$("#opts").val(data);
});
If anyone can help, it'd be greatly appreciated.
Cheers, JV
This works for your example.
$('input[type=submit]').on('click', function(evt) {
var selectedValues = [];
var url = '/imagery/image-search.aspx?search=';
$('input[type=checkbox]:checked').each(function() {
selectedValues.push($(this).val());
});
url += selectedValues.join(' ');
window.location = url;
});​
I am still not clear. But here is a code where you can build an string and pass it
<script type="text/javascript">
function fnc()
{
elements=document.getElementById("BoostMasterForm").elements;
str="";
for(i=0;i<elements.length;++i)
{
if(elements[i].type=='checkbox' && elements[i].checked)
str=str+elements[i].value;
}
alert(str);
//alert(window.location.href+'?str='+str);
//document.getElementById("aform").submit();
}
</script>
<form id="BoostMasterForm" onsubmit="fnc()">
<div class="checkboxes">
<ul>
<li>
<input type="checkbox" id="search1" name="search" class="options" value="one">
<label>one</label>
</li>
<li>
<input type="checkbox" id="search2" name="search" class="options" value="two">
<label>two</label>
</li>
<li>
<input type="checkbox" id="search3" name="search" class="options" value="three">
<label>three</label>
</li>
</ul>
<input type="submit" value="Submit"/>
</div>
</form>

Categories

Resources