Click on links that add text values to inputs - javascript

What I'm trying to do! Rank your top 10 movies in order from 1-10.
When a link is clicked it should add the text value to the input and a button that removes the value. The process should be repeated until all inputs have a value.
My horrible code!
When I click a link, it adds the value to all inputs. How do I click a link add the value to input1, click another link add the value to input2, etc.
HTML
<div class="movies">
Titanic
Rainman
Forrest Gump
</div>
<ol>
<li>
<input type="text">
<button class="remove">X</button>
</li>
<li>
<input type="text">
<button class="remove">X</button>
</li>
<li>
<input type="text">
<button class="remove">X</button>
</li>
</ol>
jQuery
$('.movies a').click(function() {
var value = $(this).text();
var input = $('input')
input.val(value);
$('button').show();
});
$('button').click(function() {
$('input').val("");
$(this).hide();
});
See Demo on Fiddle

You can use .filter() to select the next input with no current value.
$('.movies a').click(function() {
var value = $(this).text();
var input = $('input').filter(function () {
return this.value === ''
}).eq(0);
input.val(value);
input.next().show();
});
Here is a demo: http://jsfiddle.net/yp2ee/3/
The above code will only select input elements where the value is blank and then it only selects the first one returned by the .filter() function. This way you only change the value of a single input and only the first blank one.
I also updated the show/hide code for the buttons by showing and hiding the element relatively to the input element or button element clicked:
input.next().show();
UPDATE
You can use .data() to store the state of the links so you can only add a movie once:
$('.movies a').data('clicked', false).click(function() {
if ($(this).data('clicked') === false) {
$(this).data('clicked', true);
...
}
});
Then in your "X" button click event handler you can change the data regarding that value before removing the value:
$('button').click(function() {
var val = $(this).prev().val();
$('.movies a').filter(function () {
return $(this).text() === val
}).data('clicked', false);
$(this).prev().val("");
$(this).hide();
});
Here is a demo of my update: http://jsfiddle.net/yp2ee/7/

Another way: not upto standards, but readable
Modified the HTML a bit by adding classes and ids
http://jsfiddle.net/yp2ee/5/
$('.movies a').click(function() {
var value = $(this).text();
var id = $(this).attr('id');
$('.'+id).val(value).show();
$('.'+id).next('button').show();
});
$('button').click(function() {
$(this).prev('input').val("");
$(this).hide();
});

You are simply selecting the elements with its tag name. It will return collection of elements. So we don't need that. Right.? so what should we do is we have to filter the required element by using .filter() function by supplying the necessary condition[empty] to it.
Ok now we are having chances to get more than one empty text boxes, so in that situation we have to use .first() to select the first element from that collection.
Try,
$('.movies a').click(function() {
var value = $(this).text();
var input = $('input')
.filter(function(){ return $.trim($(this).val()) == ""; })
.first();
input.val(value);
input.next('button').show();
});
$('button').click(function() {
$(this).prev('input').val("");
$(this).hide();
});
The above explanations would have given a minimum understanding about the mechanism. Ok now come to the point .next() and .prev(). Again you are selecting those buttons using the tag name. So actually what we need at this situation is to select the button next to the input box and vice versa. So we could use that both to accomplish what we needed.
DEMO

Related

Disable a particular span using jQuery

I am creating a calendar event app where you can save people's birthday dates and edit people's names or dates whenever you want.
To display stored events I am using a forEach loop in JSP. I have a span named ld-option-okay-edit in each div. You can edit previous data after you click on that span and save your data.
But before clicking on the save button I am checking whether any field in a particular div is empty or not, using a jQuery hover function.
If any field is empty then I am disabling the span element so that it can't forward request to the servlet, but the problem is I am not able to disable it.
??????
THE PROBLEM
???????
My question is how can I disable a span through jQuery, or how can I prevent the onclick event of a span using jQuery?
Here is my code:
<c:forEach items="${relativeUser}" var="user">
<div class="elementsdiv">
<form action="<c:url value=" ******">" method="post">
<div class="cld-option-okay" >
<span class="glyphicon glyphicon-ok cld-option-okay-edit" name="cld-option-okay-edit" ></span>
</div>
<div class="cld-option-name" >
<input class="cld-name-input" value="${user.name}" placeholder="Name of the person" type="text" name="name">
</div>
</form>
</div>
</c:forEach>
What I have tried until now in jQuery is:
$(".elementsdiv").each(function (i, data) {
$($(data).find('.cld-option-okay')).hover(function (e) {
e.preventDefault();
if ($($(data).find('input[name="name"]')).val() === "") {
$($(data).find('span[name="cld-option-okay-edit"]')).addClass('disabled');//in this line i am getting trouble
}
}
});
For that line I even tried:
1)$($(data).find('span[name="cld-option-okay-edit"]')).attr("disabled","true");//with single quote also
2)$($(data).find('span[name="cld-option-okay-edit"]')).attr("disabled","disabled");//with single quote also
3).prop("disabled", true );
4).attr('disabled', '');
5).attr("disabled", "disabled");
6).off( "click", "**" );
7).unbind( "click", handler );
but when I apply:
`$($(data).find('span[name="cld-option-okay-edit"]')).hide()`;//it is applying
**********************
`$($(data).find('span[name="cld-option-okay-edit"]'))`till here code is working fine my problem is in applying disable.
previously i applied disable like below
$('.cld-option-okay-edit').addClass('disabled');
but it disables okay span in all divs
*************************
For enable or disable a span, you could do it like this:
var isEmpty = false;
$('#myDiv > input').keyup(function(){
isEmpty = false;
$('#myDiv > input').each(function(i,obj){
if(this.value == ""){
isEmpty = true;
return false;
}
});
// Styles for the span.
if( ! isEmpty){
$('#myDiv > span').removeClass('disabled');
} else {
$('#myDiv > span').addClass('disabled');
}
});
$('#myDiv > span').click(function(){
if(isEmpty){
alert("disabled");
} else {
alert("enabled");
}
});
I think this is what your code should look like based on what you have written, but I am not sure it is actually what you want to happen. If you want to disable it, you need to use prop()
$(".elementsdiv").each(function() {
var elem = $(this);
elem.find('.cld-option-okay').hover(function(e) {
if (elem.find('input[name="name"]').val() === "") {
elem.find('span[name="cld-option-okay-edit"]').addClass('disabled'); /*.prop("disabled",true); */
}
});
});

Can't toggle the text

[Fiddle]
In the example, I'm trying to make each pair of buttons toggle the text by matching data attributes. I can change the text from "Add" to "Remove on click. But I can't toggle it back to "Add" on second click. Can anyone tell me what's the problem?
HTML:
<div class="yellow"><button class="my_choice" data-term="A">Remove</button>
<button class="my_choice" data-term="A">Remove</button>
</div>
<div class="black">
<button class="my_choice" data-term="B">Add</button>
<button class="my_choice" data-term="B">Add</button>
</div>
jQuery:
$('.my_choice').click(function(){
var dataterm = $(this).data('term'),
my_choice = $('.my_choice[data-term='+dataterm+']')
if (my_choice.text() == "Remove")
{
my_choice.text("Add")
}
else
{
my_choice.text("Remove")
}
});
Just change the conditional to reference the clicked item, not the all the matching buttons
if (my_choice.text() == "Remove")
to:
if ($(this).text() == "Remove")
FIDDLE
As you have it, you're trying to read the text() from multiple buttons, which is why it's not working. You need to limit the text() to read from just one button.
Edit:
Updated my answer to reference the fiddle.
you are getting text using class selector so its returning text of all elements with class my_choice which is in this case addadd instead of add and for remove case removeremove instead of remove so use $(this).text() to get current clicked one text.
so you have to do like this:
$('.my_choice').click(function(){
var text= $(this).text();
var dataterm = $(this).data('term'),
my_choice = $('.my_choice[data-term='+dataterm+']')
console.log(my_choice.text())
if (text == "Remove")
{
my_choice.text("Add")
}
else
{
my_choice.text("Remove")
}
});
FIDDLE DEMO
Demo
As i earlier pointed out your code always entered else case
$('.my_choice').click(function(){
var dataterm = $(this).data('term'),
if ($(this).text() === "Remove")//change only applied in your code and added some semi colon
{
my_choice.text("Add");
}
else
{
my_choice.text("Remove");
}
});

how to know the old value of an element onChange or onTrigger in JQuery?

I have a button :
<button id="btn1">55</button>
And so I change the button value to test2
$('#btn1').text("22");
I want to show a background-picture if the buttons oldValue greater then the newValue.
How can I get the old value from this button?
"I have over 100 buttons and they are changing dynamically."
Update: Isn't there an event that fires before it changes?
You could use jQuery's .data() call and store it for retrieval as needed.
For instance, say you HTML is:
HTML
<form action="#" method="GET">
<input type="text" value="369" />
<button id="btnID">420</button>
</form>
You could easily first gather the data needed and asign it to each element:
Opening script
$("button") // would simply grab all buttons, you can use whatever css selector
.each(function(i) {
$(this).data("prevVal", parseInt($(this).text()));
});
You can then later check this value against a new value as needed:
... some change function
$('#btn1').text("22");
if ($('#btn1').data("prevVal") > 22) {
// do work
}
$('#btn1').data("prevVal", 22)
Just FYI
If you were using inputs instead it would be easier:
$("input").each(function(i) { $(this).data("prevVal", parseInt($(this).val())) })
.on("change", function(e) {
var newVal = parseInt($(this).val());
if ($(this).data("prevVal") > newVal) {
// do work
};
$(this).data("prevVal" newVal);
});
Or if you wanted to maintain a list of values:
$("input").each(function(i) {
$(this).data("vals", new Array());
$(this).data("vals").push(parseInt($(this).val()));
})
.on("change", function(e) {
$(this).data("vals").push(parseInt($(this).val()));
var vals = $(this).data("vals");
if (vals[vals.length-1] > vals[vals.length-2]) {
// do work
};
});
You need to compare it before changing value.
For example
$('#btn1').text(function (index, old) {
if (parseInt(old) > 22) {
//change background image
}
return "22";
});
FIDDLE
Unless you preserve it before the change you cannot get the old value. The change event is fired after the value has been changed already.
Not sure where you want the old value.. but if it while changing the text then use the function to change the text.
$('#btn1').text(function (index, oldvalue) {
console.log(oldvalue);
return "test2";
});
<button id="btn1">test1</button>
​$(document).ready(function(){
var i=1;
$('#btn1').click(function(){
$(this).data('old', $.trim($(this).text())).text('btn'+(++i));
alert( $(this).data('old'));
});
});​
for demo
use jQuery.data() to store data associated with the specified element and you will be able to get it just by accessing the same element.
Here's the link to show you how to use jQuery.data();
Here's the code using a more convenient .data() link
Set
$("#btn1").data("oldVal", $("#btn1").html());
Get
$("#btn1").data("oldVal");
Fiddle

JQUERY how to select items

i need to select some items and check if value are not empty, and hide the previus item....but not work....
for example:
<script>
if($('input[type=text],input[type=email],input[type=password]').val() != ""){
$(this). prev().hide();
}
</script>
<div class="prova"></div>
<input type="text">
<div class="prova"></div>
<input type="text">
<div class="prova"></div>
<input type="text">
when i load page the previus div for every input, not hide....someone can help me?
When you call a call val() method on a set of matched elements it gets the current value of the first element in the set of matched elements. So you should run a loop check the value of each element and then hide previous element. Try this.
$('input[type]').each(function(){
if($(this).val()){
$(this).prev().hide();
}
});
If you have to show the previous element if there is value then you can use this script.
$('input[type]').each(function(){
$(this).prev().toggle($(this).val() == '');
});
.toggle(showOrHide) - Display or hide the element based on the boolean input.
You want to do this:
$(':input').each(function() {
if ($(this).val() != "") {
$(this).prev().hide();
}
});
You can do it by passing a function to .val().
var inputs = $('input[type=text],input[type=email],input[type=password]');
inputs.val(function(i,curr_val){
if( curr_val )
$(this).prev('.prova').hide();
return curr_val;
});

how to set focus to first editable input element in form

Dynamically created form contains input elements. First elements may be disabled or readonly.
I tired code below to set focus to first elemnt which accepts data to enable fast data enttry form keyboard.
However if form fist element is disable or readonly, focus is not set.
How to set focus to first element which accepts data ?
<form style='margin: 30px' id="Form" class='form-fields' method='post' target='_blank'
action='Report/Render'>
...
<input id='_submit' type='submit' value='Show report' class='button blue bigrounded' />
</form>
<script type="text/javascript">
$(function () {
var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea');
elements[0].focus();
elements[0].select();
});
</script>
Update
There are also hidden input fields, sorry. Answers provided set focus to hidden element. Answr containing function does not find any element.ˇ
Here is the update testcase:
$(function () {
$("#form :input:not([readonly='readonly']):not([disabled='disabled'])").first()
.focus();
});
How to set focus to vist visible, enabled and not readonly element ?
Update 3
I tried Row W code where input element was added.
Now it sets focus to second element. Testcase is shown at Revision 5 of Rob W's answer
Use the following code:
var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea').filter(function(){
return !this.readOnly &&
!this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none";
});
elements.focus().select();
If you only want to select the first element, the following code is more efficient:
$('#Form').find(':text,:radio,:checkbox,select,textarea').each(function(){
if(!this.readOnly && !this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none") {
this.focus(); //Dom method
this.select(); //Dom method
return false;
}
});
Update: if you want to have the elements in the same order, use:
var elements = $("#form").find("*").filter(function(){
if(/^select|textarea|input$/i.test(this.tagName)) { //not-null
//Optionally, filter the same elements as above
if(/^input$/i.test(this.tagName) && !/^checkbox|radio|text$/i.test(this.type)){
// Not the right input element
return false;
}
return !this.readOnly &&
!this.disabled &&
$(this).parentsUntil('form', 'div').css('display') != "none";
}
return false;
});
Use jQuery's :not() selector:
$("#myForm :input:not([readonly='readonly']):not([disabled='disabled']):reallyvisible").first()
.focus();
Here's a working fiddle.
EDIT:
To meet the new requirement you posted in the comments, you'll have to extend the :visible selector to check for parent visibility (untested):
jQuery.extend(
jQuery.expr[ ":" ],
{ reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

Categories

Resources