how to set selected li value to input with jquery - javascript

I don't know how to use jquery the get the result:
click the li will add select class and remove others selected li
set the select li datavalue to input(id:sizevalue)
make sure the li list should be selected one when click submit button
<form name="form">
<style>
#sizelist ul{list-style-type:none;}
#sizelist ul li{float:left;display:inline;margin-right:5px;width:auto;overflow:hidden;}
#sizelist ul li a{display:block;border:1px solid #CCCCCC;padding:5px 6px 5px 6px;margin:1px;}
#sizelist ul li a:hover{border:2px solid #FF6701;margin:0px;}
#sizelist .select a{border:2px solid #FF6701;margin:0px;}
</style>
<ul id="sizelist">
<li datavalue="S">S</li>
<li datavalue="M">M</li>
<li datavalue="L">L</li>
<li datavalue="XL">XL</li>
</ul>
<input id="sizevalue" size="15" name="size" type="text" />
<input type="button" value="submit"/>
</form>
plz help

Try this one:
HTML
<ul id="sizelist">
<li>S</li>
<li>M</li>
<li>L</li>
<li>XL</li>
</ul>
<input id="sizevalue" size="15" name="size" type="text" />
jQuery
$('#sizelist a').on('click', function(e) {
e.preventDefault();
// This removes the class on selected li's
$("#sizelist li").removeClass("select");
// adds 'select' class to the parent li of the clicked element
// 'this' here refers to the clicked a element
$(this).closest('li').addClass('select');
// sets the input field's value to the data value of the clicked a element
$('#sizevalue').val($(this).data('value'));
});
Take note of the changes that I made:
-- replaced datavalue with data-value so as to be able to use .data() method of jQuery
-- transferred the data-value attributes to the a elements because they're the ones who actually gets clicked
-- replaced the javascript:void(0) in the href because it just does not do anything

The following will achieve want you want:
HTML
<form name="size-form">
<ul id="sizelist">
<li data-value="S">S</li>
<li data-value="M">M</li>
<li data-value="L">L</li>
<li data-value="XL">XL</li>
</ul>
<input id="sizevalue" size="15" name="size" type="text" />
<input type="submit" value="submit"/>
</form>
JavaScript
$("#sizelist").on("click", "a", function(e){
e.preventDefault();
var $this = $(this).parent();
$this.addClass("select").siblings().removeClass("select");
$("#sizevalue").val($this.data("value"));
})
$("form[name=size-form]").submit(function(e) {
//do your validation here
if ($(this).find("li.select").length == 0) {
alert( "Please select a size." );
e.preventDefault();
}
});
jsFiddle Demo
You should use the data-* attribute to store the data.

I think this code will work for you:
$('#sizelist a').on('click', function(event) {
// Clear previous selection
$('#sizelist li').removeClass('selected');
// Add selection css class
$(event.target).parent('li').addClass('selected');
// Change value in input
$('#sizevalue').val($(event.target).parent('li').attr('datavalue'));
});
NB. The preferred way of adding additional attributes in HTML is to prefix them with data-.

Related

How to fetch the value in input hidden field through li data-val

I want to the selcted data-id value to be fetch in input hidden field
Here is my source code:
jQuery('li').click(function() {
$('#car').html(jQuery(this).attr("data-val"));
}); <
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-val="all">Allahabad</li>
<li data-val="pra">Pratapgarh</li>
<li data-val="kan">kanpur</li>
<li data-val="chd">Chandigarh</li>
<li data-val="ldh">Ludhiana</li>
</ul>
<input type="text" name="car" id="car" value=" ">
.html() will set the html contents for elements(which is invalid for input elements). You need to set value and not html. use .val():
$('#car').val($(this).attr("data-val"));
change this,html function is used for setting the html content for setting the values use val() function
$('#car').val(jQuery(this).attr("data-val"));

JQuery Multiple Hidden Values

I have the following HTML;
<ul class="list-group">
<li class="list-group-item">
www.andrewspiers.co.uk
<input type="hidden" name="url" value="www.andrewspiers.co.uk">
</li>
<li class="list-group-item">
wikipedia.org
<input type="hidden" name="url" value="wikipedia.org">
</li>
</ul>
The plan is to add a button to each row and then get the value from the hidden field when the button is clicked.
I have this;
alert( $('input[name="url"]').val() );
But that returns the value of the first row no matter which button is clicked.
This should work:
$('button').click(function(){
console.log($(this).closest('li').find('input[name="url"]').val())
})
You need to use $(this) within the click function to refer to that specific element and then traverse the DOM accordingly (multiple ways to skin a cat on this one) to get the hidden input.
jsFiddle example
Assuming your buttons are placed inside the same li, you need a more specific selector:
alert( $(this).siblings('input[name="url"]').val() );
You can add buttons like this :
$('.list-group-item').each(function(){
$(this).append('<input class="clicked" type="button" value="Click me"/>')
})
YOu can then get value of each hidden according to the button like this:
$('.clicked').on('click',function(){
var hiddenval =$(this).parent().find('input[name="url"]').val();
console.log(hiddenval);
})

A puzzling click event : Why such behaviour?

I was recently testing the click event (finding a textbox upon click) of a <label> and found something unusual.
In the HTML markup,
If the <input> is inside the <label>, the click event on that
label is firing two times
If the <input> is outside the <label>, the click event is
functioning as expected
To better understand what I'm trying to put forward, please refer to the fiddle at JS Fiddle
I'm baffled because of this and can't figure out the reason behind it. Any takers?
If the <input> is inside the <label>, the click event on that label is firing two times
Because events 'bubble' up through the DOM, from the element recieving the initial event (the event.target, here the <input />) through ancestors. Because the listener is attached to the parent of the <input /> it first fires on the click detected on its descendant, and then again when the click bubbles to itself.
To prevent this, you can use event.stopPropagation() to prevent bubbling.
Because the event, in this case, has already bubbled to the <label> element at the point that the alert()/event-handler is fired, you'll have to explicitly call event.stopPropagation() on the <input /> itself, rather than in the event-handler attached to the <label>:
$(function() {
$('label input').click(function(event) {
event.stopPropagation();
});
$(".v1 li label").click(function() {
var ct = $(this).find("input").val();
alert(ct);
});
$(".v2 li label").click(function() {
var ct = $(this).parent().find("input").val();
alert(ct);
});
});
ul {
padding: 10px;
}
li {
list-style: none;
margin-bottom: 5px;
}
li label {
display: block;
background-color: #f0f0f0;
padding: 5px;
cursor: pointer;
border: 1px solid #ccc;
}
li input {
display: none;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3><i>input</i> inside <i>label</i></h3>
<ul class="v1">
<li>
<label for="l1">
<input type="radio" name="a" value="1" id="l1" />First</label>
</li>
<li>
<label for="l2">
<input type="radio" name="a" value="2" id="l2" />Second</label>
</li>
<li>
<label for="l3">
<input type="radio" name="a" value="3" id="l3" />Third</label>
</li>
</ul>
<hr />
<h3><i>input</i> outside <i>label<i></h3>
<ul class="v2">
<li>
<label for="ll1">Fourth</label>
<input type="radio" name="b" value="4" id="ll1" />
</li>
<li>
<label for="ll2">Fifth</label>
<input type="radio" name="b" value="5" id="ll2" />
</li>
<li>
<label for="ll3">Sixth</label>
<input type="radio" name="b" value="6" id="ll3" />
</li>
</ul>
References:
click().
event.stopPropagation().
In your case, click event is propagating from label to input and then again to label, hence you can find two alerts.
You can use below code when we can check the target element tag name and if it is INPUT then return otherwise process further.
$(".v1 li label").click(function(event){
if(event.target.tagName=='INPUT')
return false;
var ct= $(this).find("input").val();
alert("first "+ct);
});
JSFiddle Demo

Submit filter form on link click

I'm trying to make something a bit like this:
This is my code: http://jsfiddle.net/928Dj/19/
$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
var cache = $(this).next('ul');
$('#filter ul:visible').not(cache).hide();
cache.toggle();
});
I'm trying to make it degradable so without javascript they can submit the form to adjust the results, but with javascript they can just click the text of the desired result.
Question A
How can I make it so by them clicking the text alone, with javascript enabled, it not only selects the radio button but also submit the form.
Question B
Is my code the right approach to achieve this desired outcome?
Replace the radio buttons with submit buttons.
<input type="submit" name="status" value="Status 1">
i think google uses <a> tag instead <input> and (but i'm not sure) catches the click and makes a ajax call to update only the result (without any form)... like: http://jsfiddle.net/928Dj/25/
HTML, change <input> in <a>:
Status 1
JS
$('ul.opt a').click(function(e){
e.preventDefault();
$(this).parents(".opt").find("a").removeClass("active");
$(this).addClass("active");
$.get($(this).attr("href"),function(res){
//do something with response
});
});
On <a> click the JS simply perform search.action (or other search service) with sortDate=status1 like parameter via AJAX, for sort the result.
You can concat the sorting parameters status=status1&date=date1 for multiple sorting.
I don't know if there are any ways to perform the submit without using javascript (and without reload all page).
I've updated your fiddle with submit buttons that are hidden if javascript is enabled.
<div>
<form action="/echo/html/">
<ul id="filter">
<li> Any status ▾
<ul class="opt">
<li>
<label>
<input type="radio" name="status" />Status 1</label>
</li>
<li>
<label>
<input type="radio" name="status" />Status 2</label>
</li>
<li>
<input type="submit" value="submit"/>
</li>
</ul>
</li>
<li> Any date ▾
<ul class="opt">
<li>
<label>
<input type="radio" name="date" />Date 1</label>
</li>
<li>
<label>
<input type="radio" name="date" />Date 2</label>
</li>
<li>
<input type="submit" value="submit"/>
</li>
</ul>
</li>
</ul>
</form>
</div>
<div id="results">
Filtered results go here
</div>
<script>
$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
var cache = $(this).next('ul');
$('#filter ul:visible').not(cache).hide();
cache.toggle();
$('#filter li input[type=submit]').hide();
});
$('#filter input[type=radio]').click(function() {
var $form = $(this).closest('form');
$('#results').html('filtering...');
$.post($form.attr('action'),$form.serialize(),function(response) {
if ( response ) {
$('#results').html(response);
} else {
$('#results').html('no results found');
}
});
});
</script>

find closest class

I want to find a closest class of the given object. My markup looks like this:
<div class="table_settings">
<div style="float:left;">
<div class="stats_options" id="yearSelector" style="width:140px;">
<div style="float:left"><span class="optionValue"></span></div>
<div style="float:right; margin-top:11px;"><img src="../images/arrow_down.png" /></div>
<div class="clear"></div>
</div>
<div id="yearSelectorOptions" class="option_list" style="width:160px; display:none; margin-top:0px;">
<ul>
<li><input type="radio" name="year" value="2" style="display:none;" alt="Winst en verlies" checked="checked" />Winst en verlies</li>
<li><input type="radio" name="year" value="1" style="display:none;" alt="Eindbalans" />Eindbalans</li>
</ul>
</div>
</div></div>
The jquery looks like this:
$(".option_list ul li").click(function()
{
$(this).children('form input[type="radio"]').prop('checked', true);
value = $(this).children('input[type="radio"]:checked').attr('alt');
$(this).parents('.table_settings').children('.optionValue').text(value); }
What I want is when I click on the [li] that the value of the clicked [li] gets into the class optionValue.
I want to duplicate this list so it have to work for more lists on one page.
I hope someone can help me.
Thanks in advance!
//select all the `<li>` elements that are the children of the `<ul>` element that is the child of the `.options_list` element
$(".option_list").children('ul').children().click(function() {
//select the first ancestor element with the `.table_settings` class,
//then select the `.optionValue` element that is a descendant of the `.table_settings` element,
//then set it's text to that of the input element inside the `<li>` element clicked
$(this).closest('.table_settings').find('.optionValue').text($(this).children().val());
});
Here is a demo: http://jsfiddle.net/rpVxV/
Try this:
$('.option_list')
.find('li')
.click(function () {
var $radio = $(this).children(':radio'),
value = $radio.attr('alt'), // Or `$(this).text()` ...
$(this)
.parents('.table_settings')
.find('.optionValue')
.text(value);
});
Your code is basically not working because of this line:
//`.optionValue` is not IMMEDIATE
// children of `.table_settings`
// so it won't work
$(this).parents('.table_settings').children('.optionValue').text(value); }

Categories