Append in <li><input/></li> works just one time - php

I would like to make a li inputable after the page being execute. I want the li function close to word office format. I mean, when we write on first list then ENTER it, it would focus on second list and ect. and this is my code I've made before:
<div class="writeform">
<label class="subtitle">ingredients</label>
<ol>
<li><input class="formxyz globalwrite" id="ingred" name="ingred" placeholder="ingredients"></input>
</li>
</ol>
</div>
and this is the script in ajax
$('input#ingred').on('keydown',function(e){
if(e.which == 13) {
$('ol').append('<li><input class="formxyz globalwrite" id="ingred" name="ingred" placeholder="ingredients"></input></li>');
$('input#ingred').focus();
}
});
when I run this code, and write in the 1st line then I press ENTER, the second li shows up. But when I write in 2nd li and press enter, nothing appended. How can I make this append function work continously when I press ENTER key?

You cannot have duplicate uses of ID values - it is not valid HTML, and your selector for the input element would not work properly. The same thing would be true with using a class, even though it is valid to have multiple uses of a class, the selection would select all matching elements. You would need to generate a unique ID, or use a different selector to select the last input element, such as the jquery .last() selector.

If there are two ID selectors of the same name , jQuery only select the first one.

You should bind the keydown event using delegation method, like this:
Change this:
$('input#ingred').on('keydown',function(e) {
Into this:
$(document.body).on('keydown','input#ingred',function(e) {
Because the first syntax will not bind to elements which are created later (dynamically).
UPDATE
For more correct way, you should make it bind to class or name attribute rather than id, because id id originally for naming elements and should be unique.
I think this is what you need in correct way: :D
$(document.body).on('keydown','input.formxyz',function(e) {
or:
$(document.body).on('keydown','input[name="ingred"]',function(e) {
Good luck!

Related

Change the value of second select on first select

I'm sorry I haven't included "my attempt" as such with this one, I'm useless with jquery so need some advice!!
I would like to change the value of a second selctor based on the results of the first.
I have a database of builders and regions with the headers builder_name and builder_region. The list ends up looking like this ...
builder_1 region_1
builder_1 region_2
builder_2 region_1
builder_3 region_1
builder_3 region_2
builder_3 region_3
(You get the idea)
I'm using the following in the form I've built to get a list of the builders for the first select box ...
echo '<select class= "ml-select" name="gen_builder">';
echo '<option value=" ">Select Builder</option>';
while($row = mysql_fetch_array($rsBUILDER)) {
if($linebreak !== $row['builder_name']) {
echo '<option value="'.$row['builder_name'].'">'.$row['builder_name'].'</option>';
}
else {echo "";}
$linebreak = $row['builder_name'];
}
echo '</select>';
The $linebreak is to get rid of the duplicate builder names from the list, which works a treat.
What I would like to achieve is a second selector that selects the regions available, dependant upon the builder that has been selected in the first option. I hope this makes sense????
The second query needs to look at the builder selected in the first selector and filter out just the regions that are in rows with the builder name form selector one.
Please do say if you need further information, I'm not great at explaining myself.
As you said you don't have experience with jQuery or Ajax, I'll post my answer with as many comments as possible. I will assume that you have two select dropdowns in your page.
The first one contains the builders, so it will have id="builders".
The second one contains the regions, so it will have id="regions".
From what I understand, the first select will be exactly the one you posted in your question, generated server-side (by PHP). I only ask that you please make a slight change on it, making each option value be equal to the builder's database ID, and not its name (unless the builder's primary key is their name, and not an ID). This will make no difference for the final user but will be important for our jQuery solution. The second one will be empty, as the idea is to fill it dynamically with the regions related to the builder selected in the first dropdown.
Now let's get to the jQuery code:
//Everything that goes below this first line will be ready as soon as the page is fully loaded
$(document).ready(function() {
//The following code defines an event. More precisely, we are defining that the code inside it will run every time our select with id "builders" has its value changed
$('#builders').change(function() {
//$(this) is our builders select. $(this).val() contains the selected value, which is the ID of our selected builder
var currentValue = $(this).val();
//Now, this is our Ajax command that will invoke a script called get_regions.php, which will receive the builder's ID in $_GET['builder_id'] and you can use to query your database looking for all regions related to this builder. Make sure to create an array with the returned regions. Your get_regions.php's last line should be echo json_encode($regions);
$.get("get_regions.php", {'builder_id': currentValue}, function(data) {
//Inside this function is the code that will run when we receive the response from our PHP script. It contains a JSON encoded list of regions, so first of all we need to parse this JSON
var regions = $.parseJSON(data);
//Before filling our second select dropdown with the regions, let's remove all options it already contains, if any
$('#regions').empty();
//Now, all there is left is to loop over the regions, adding each as an option of the regions dropdown. I'll do it the universal way
for (var i = 0; i < regions.length; i++) {
var regionOption = '<option value="'+regions[i]['region_name']+'">';
regionOption += regions[i]['region_name'];
regionOption += '</option>';
$('#regions').append(regionOption);
}
});
});
});
Despite any syntax errors (can't test the code from here) this should do the trick. Hope the comments were clear enough for you to understand how things work in jQuery.

how to get the html value of a brother div

Im sorry for the title but i did not know how to frame a title for this question
Question:
i have a container div and two child divs.the first child div contains a numeric value which i want incremented every time the second child div is clicked
CODE:
<div class="container1">
<span class="like_counter">2</like>
<span class="like_unlike">Like</span><!--if the text within is like then on click it will change the inner text to unlike and increment the value in like counter by 1.if it is unlike it will decrement it by 1 and change inner text to Like-->
</div>
Note the first child selectors are not an option because it would affect every first child div
Answers, used prev function not very good, if the order of items changes, code stop working.
Try this:
$(".like_unlike").bind("click", function(e) {
e.preventDefault();
var likeCounter = $(this).siblings(".like_counter");
likeCounter.html(parseInt(likeCounter.html()) + 1);
});
You can use
$(this).prev()
And some more interesting sibling searches along-with others are listed here http://home.techphernalia.com/70480/HTML/Selector.html
It's called sibling. You can use
$(this).prev();
https://api.jquery.com/prev/

How to make ID's unique on this 'Click to Reveal' script

I'm trying to add this script to my site but there are a list of the same element generated by the script "voucherCode" so am struggling here because when I test it, only the first element will 'reveal' no matter which one is clicked...
<!--EDIT-->
tried calling the script using a class which works but now all of them reveal:
Like Blazemonger said, browsers will not pick up multiple elements with the same ID. Id should be unique, and if you need something that repeats then uses classes.
Update
well first of all you need to add the class instead of ID
<div class="voucherCode">
if you use jquery (call it in the header first, google jquery)
$('.trigger_class').click(function(){
//do what you need to do here when clicked
//to access all of the voucherCode class you use $('.voucherCode').css('display', 'block');
});
Update 2:
if you only want specific ones to reveal then you need identifiers on those ones (class(2 or more) or id(only 1)) then target the ones you want to show. To make it more dynamic, you can add a rev or title attribute to the trigger anchor tag, and use jquery to grab that attribute and use it as the element you want to reveal
<a class="trigger_class" rev="reveal_class_or_ID">....</a>
then in the javascript
$('.trigger_class').click(function(){
//grab the rev from the a, this is use a class (hence the . if it is using id it would be #)
$("." + $(this).attr("rev")).css('display','block');
});
Lastly don't forget to add the reveal_class_or_ID to your items
Update:
I am not good with php but it seems like you have the option to add the iterator or index to
<div class="revealVoucher" id="reveal_dynamicID">
Reveal Code
</div>
<div class="voucherCode" id="show_dynamicID">
<?=$voucher_code?>
</div>
I don't know how iterator works in php but if you know php this should make sense

Jquery onmousedown needing a double click?

I have searched before posting but none of the posts are that relevant (saying that i am new to Jquery).
My problem is when i click the "add friend" button it wont fire upon a single click but it needs a double click.
These are the relevant sections of code:
Setting the div:
$fField = <div style="display:inline; border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color#999; font-size:11px;">
Add Friend
</div>;
Javascript:
function friendArea(x){
//alert(x);
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
$('.friendSlide').hide();
}
the message to display (the one which needs 2 clicks to be displayed)
<div class="friendSlide" id="addFriend">Are you sure?</div>
Any help would be much appreciated! Oh and I'm using the latest version of jQuery.
Hmm, well, it looks like you are showing and hiding your div at the same time:
HTML:
<div class="friendSlide" id="addFriend">Are you sure?</div>
JS:
function friendArea(x){
//alert(x);
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
$('.friendSlide').hide();
}
You call friendArea('addFriend'), which is supposed to slideDown your div, but at the end of the function you hide .friendSlide, of which your div is also a class. You basically hide it every time. This can't be what you want.
Comment out that line and it works: http://jsfiddle.net/Ggdhp/
Of course, you might have had a different reason for that, but I think you are getting some divs and classes mixed up.
Note:
I would also suggest that you don't use inline css or javascript. It always makes debug much more difficult, and you miss typos as you end up having to put everything on a single line and escape quotes. For instance, color#999; in your div style is missing a colon.
I'm not entirely sure that's the relevant part of the code, but if you want to learn how to bind functions to click/doubleclick/etc:
http://api.jquery.com/category/events/mouse-events/
I assume you have a button/link somewhere that has something to the extent of:
Add Friend
What you would want to do instead is give that button a class indicating that it's an add friend button, and use jQuery to add the double click function to it.
Add Friend
$('.addFriend-button').click( function(e) {
friendArea( $(this).data('friendName') );
} );
This will cause your function to fire when the button is double clicked, not single clicked. It also allows you to only have to write 1 function, and you can pass the relevant data in using the data-* attributes on the link element.
if you want to run any code on double click over an element use jquery like this,
$('#target').dblclick(function() {
alert('Handler for .click() called.');
});
and one more thing use jquery toggle to display and hide elements like below, On your function
if you are using class name of selector use the selector like below (use .) in case of id use # with id name like above code
$('.target').toggle();
if double clicks works for you to use below code, it converts the single click to double click by jquery. Hopes this will help you
$('#target').click(function() {
$('#target').dblclick();
});

How to show/hide one dynamic element (div) at a time with jQuery

This is my first attempt at jQuery and I'm using a basic tutorial I found here: http://papermashup.com/simple-jquery-showhide-div/#
This is my current code and how the jQuery works: http://jsfiddle.net/mZQsu/
As you can see, when you click the '+/-' it opens all 4 of the tables/DIVs.
How can I modify this code to open just the relevant secondary table/div according to the original table?
(Please note the secondary tables are generated dynamically from PHP and SQL data)
Thanks.
P.S all my code is here http://jsfiddle.net/mZQsu/ instead of clogging up this question page :)
DEMO fiddle
$('.toggler').click(function() { // had to differentiate the main togglers with a new class
var ind = $(this).parents('tr').index()-1; // could change
$(".slidingDiv").eq(ind).slideToggle();
});
$('.show_hide').click(function() { // this are the 'togglers' inside the big menus
$(this).parents(".slidingDiv").slideToggle();
});
The best solution would be if you tag each of your div's with an id. E.g.
<div class="slidingDiv" id="ip_127_0_0_1">
and then modify the equivalent links to do
$("#ip_127_0_0_1").slideToggle();
so just the associated div gets expanded.
See my updated fiddle: http://jsfiddle.net/mZQsu/1/
You can use the index of the row, and toggle only the matching row of the other table using jQuery index and eq
See the relivant docs here:
jQuery index
jQuery eq
This should work:
$('.show_hide').click(function() {
$(this).parents(".slidingDiv").slideToggle();
});
Since the slidingDiv class is a direct parent of the show_hide link, I could have used "parent" rather than "parents". The latter provides more flexibility because it traverses all ancestors looking for the class.
Here is a modified code - http://jsfiddle.net/mZQsu/3/
I have added show-hide1, show-hide2, show-hide3, show-hide4.
And clicking on it opens respectively slidingDiv1, slidingDiv2, slidingDiv3, slidingDiv4.
When you are binding to an event: You can always grab that event target and reference it.
$('.show_hide').click(function(e) {
$(e.target).parent("div.slidingDiv").slideToggle();
});
.parent() is a good place to start, but .closest() also might work. That being said, this is the preferred way to go about it.
On a side note if you ever want to do the opposite you could use .not(e.target) and all the other elements except for the one your click will be called.
Since your html is PHP-generated, it should not be a problem to include unique IDs for both +- links and sliding divs, for example:
a href="#" class="show_hide" id="show_hide2"
And
div class="slidingDiv" id="slidingDiv2"
Then in your click function you get the index of the div that you want to open:
$(.show_hide).click(function(){
var $str = $(this).attr('id');
var $index = $str.charAt( $str.length-1 );
});
Now you can use index to open the div:
var divName = "#slidingDiv" + $index;
$(divName).slideToggle();

Categories