Using $('selector').each() to modify and update html of DOM elements? - javascript

I am trying to create an event listener across a bunch of links on my site. These links are generated within a loop, so I end up with <a class = "replyButton" id = "replyID"<? echo $x; ?> etc.
I'm trying to use the code below to reveal an input box when each respective link is clicked, but with no luck. I can get it to work using plain JS too, in one case, but not using JQuery, extrapolated across several like this. Any help would be really awesome.
window.onload = function(){
$('.replyButton').each(function(index){
var domElementId = "replyArea" + index;
domElementId.onclick = function() {
var replyFieldHtml = '<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>';
document.getElementById('domElementId').innerHTML = replyFieldHtml;
console.log('domElementId');
return false;
}
});
}
Edit: here is the loop im using to generate the html...
$x = 0;
while ($x < 8){
$x++;
$r = $wallarray - $x;
$postContent = $wall_content['wall_posts'][$x-1];
$postUser = getUserNameById($wall_content['userID'][$x-1]);
?>
<div class = "row">
<div class = "span6">
<div class = "span1" id = "wallPhoto"><img src ="assets/img/usr/profile_holder.jpg></div>
<div class = "span4">
<div class = "span4" id = "wallFeedStyle"><a id = "wallUserLink" href = "#"><b><? echo $postUser; ?></b></a></div>
<div class = "row">
<div class = "span5">
<div class = "span4" id = "userPost"><? echo $postContent; ?></br><p class = "wallsmall"></i>Like ยท<a class = "replyButton" id = "replyButton<? echo $x; ?>" href="#"></i>Reply</a></p></div></div>
</div>
<div class = "row">
<div class = "span5">
</div>
</div>
<div class = "row" id = "replyArea<? echo $x; ?>"></div>
</div>
<?
}
?>

You're using the variable in the wrong manner. Try this:
window.onload = function () {
$('.replyButton').each(function (index) {
var domElementId = "replyArea" + index;
$('#' + domElementId).on('click', function () {
var replyFieldHtml = '<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>';
$(this).html(replyFieldHtml);
console.log(domElementId);
return false;
});
});
}

I ended up using the code below to solve this one, after digging deeper into the history behind .on() and .bind(). Thanks for all your help!
$('a.replyButton').on("click", function(){
var index = $(this).attr('id');
$('#replyArea'+index).html('<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>');
});
I ended up changing the "replyLink" ID attribute to just the number. So there were a bunch of /<.a> with class replyButton, and ID attributes as a number. And it seems to do the job nicely, no need to setup the .each() loop too.

Related

display input in divs doesn't work

I am trying to populate divs based on input. It works fine (I tried it.) at http://jsfiddle.net/2ufnK/2/ but when I implemented it at http://communitychessclub.com/cccr-pairing/test.html it didn't work. I wonder why...
<div class = "ui-widget white"><input id = "W01" name = "w01" type = "text" onchange="screen_W01()" class = "automplete-2" autofocus></div>
<div class = "ui-widget black"><input id = "B01" name = "b01" type = "text" onchange="screen_B01()" class = "automplete-2" ></div><br />
<div class = "ui-widget white"><input id = "W02" name = "w02" type = "text" onchange="screen_W02()" class = "automplete-2"></div>
<div class = "ui-widget black"><input id = "B02" name = "b02" type = "text" onchange="screen_B02()" class = "automplete-2"></div><br />
and:
<script>
function screen_W01(){var x = document.getElementById("W01"); var div = document.getElementById('WD01'); div.innerHTML = x.value;}
function screen_B01(){var x = document.getElementById("B01"); var div = document.getElementById('BD01'); div.innerHTML = x.value;}
function screen_W02(){var x = document.getElementById("W02"); var div = document.getElementById('WD02'); div.innerHTML = x.value;}
function screen_B02(){var x = document.getElementById("B02"); var div = document.getElementById('BD02'); div.innerHTML = x.value;}
</script>
the HTML to display the values...
<div id="WD01"></div>
<div id="BD01"></div>
<div id="WD02"></div>
<div id="BD02"></div>
But it just doesn't work: the values aren't displayed. Can someone suggest a better way (jquery preferred) or correct my coding error?
I would suggest using ONE function for all inputs and corresponding divs.
It uses "string manipulation" on the input id to deduct the target's id.
$(".ui-widget input").on("change", function(){
var inputID = $(this).attr("id"); // Ex: W01
// Add the "D"
var divID = inputID.substr(0,1)+"D"+inputID.substr(1); // Ex: W + D + 01
console.log(inputID);
var inputValue = $(this).val();
$(document).find("#"+divID).html(inputValue);
});
And the markup for the inputs would be (Just remove the "onchange=...")
<div class = "ui-widget white">
<input id = "W01" name = "w01" type = "text" class = "automplete-2" autofocus>
</div>
I might be way off on this; I'm fairly new to all of this as well. I do see you have
<div class = "ui-widget white"><input id = "W01" name = "w01" type = "text" onchange="screen_W01()" class = "automplete-2" autofocus></div>
and
function screen_W01(){var x = document.getElementById("W01"); var div = document.getElementById('WD01'); div.innerHTML = x.value;}
where your id = "W01" for both, but in your HTML values you have
<div id="WD01"></div>
which has id="WD01". Could this be the reason it's not working? All of the HTML values have the added 'D'. That's the only thing I can see based off what's here.

can't access to value tag for show data in jquery , mysql , php

the below code is jquery code:
$(document).ready(function(){
$("#srchtxt").keyup(function(){
var addresshome = $("#srchtxt").val();
$.post("adrespath",{address:addresshome},function(res){
var json = JSON.parse(res);
var lenths = json.length;
for(var i = 0;i <= lenths;i++)
{
var city = json[0];
var state = json[1];
var optionli = "<li id='item'><a href='#' value='"+res+"'>"+city+"-"+state+"</a></li>";
$(".resultsearch .ul").append(optionli);
}
});
});
$(".ul li#item a").each(function(){
$(this).click(function(e){
e.preventDefault();
var index_address,address;
index_address = $(this).parent().index();
alert(index_address);
address = $(this).eq(index_address).attr("value");
$("#srchtxt").attr("value",address);
});
});
$("#srchbtn").click(function(){
alert($("#srchtxt").val());
});
});
and the below code is html code:
<input type="search" name="srchtxt" id="srchtxt"/>
<div class="resultsearch">
<ul class="ul">
</ul>
</div>
and the below code is php code:
<?php
$address = $_POST['address'];
$querysrch = "select city,state,bolv from tbl where city like '%".$address."%' or state like '%".$address."%' or bolv like '%".$address."%'";
$ressrch = mysqli_query($cnt,"SET NAMES 'utf8'");
$ressrch = mysqli_query($cnt,"SET CHARACTER 'utf8'");
$ressrch = mysqli_query($cnt,"SET character_set_connection = utf8");
$ressrch = mysqli_query($cnt,$querysrch);
$arry = array();
if(mysqli_num_rows($ressrch) > 0){
while($row = mysqli_fetch_assoc($ressrch)){
$addressres = $row['city']."-".$row['state']."-".$row['bolv'];
$arry[] = $row['city'];
$arry[] = $row['state'];
}
}
else
{
$arry .= "<li id='item'><a href='#' value='not found'>notfound</a></li>";
}
echo json_encode($arry);
?>
i want when keyup chaarcter show result and when i select the li a tag show to me value tag in jquery please help me
i think your code also works fine but you forget to add id on anchor tag while appending it on ul. if you append more then one anchor tag than you should use class because there can't be a two anchor tag with same id which will make conflict. or you can use onclick attribute on your anchor tag
append your anchor tag like this
var optionli = "<li id='item'><a href='#' value='"+res+"' onclick='show_value()'>"+city+"-"+state+"</a></li>";
and js function
function show_value(){
alert($("#srchtxt").val());
}

Get values by class

I tried for hours but could not find any solution.
Simplified my code looks like following.
PHP :
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
...
}
?>
JS :
$(document).ready(function(){
$("._submit").click(function(){
?? var _title = document.getElementById('_title'),
?? _file = document.getElementById('_file');
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('title', _title.value);
...
</script>
I don't know how to get the data by class. By ID it is working, but i can't use IDs, because there would be several same IDs because of the foreach loop.
Tried this as well without success:
var _file = document.getElementsByClassName('_file');
I hope somebody can help me.
Misch
You can wrap your elements in container div like
<?php
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<div class='container'>
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
</div>
}
?>
Then use .closest() to traverse up the container. After wards you simply use find to get the desired elements.
<script>
$(document).ready(function(){
$("._submit").click(function(){
var container = $(this).closest('.container');
var _title = container.find('._title'),
var _file = container.find('._file')[0];
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('title', _title.value);
//Rest of your code
});
});
</script>
Since you're using jquery you could use .each() function and class selector . to loop through all the element with same class :
$('.class').each(function(){
var input_value = $(this).val();
})
Since you have more than one field with class _title and _file you should pass them as array to Formdata() using array signs [] :
var data = new FormData();
$('._file').each(function(){
var _file = $(this).val();
data.append('SelectedFile[]', _file.files[0]);
})
$('._title').each(function(){
var _title = $(this).val();
data.append('title[]', _title);
})
Hope this helps.
One more thing you can do a bit same as #satpal
Wrap your code in a div element.
PHP:
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<div> <!-- wrapper -->
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
</div>
}
?>
Then try following code.
JS:
$("._submit").click(function(){
var title = $(this).siblings('._title').val();
var file = $(this).siblings('._file')[0].files[0];
var data = new FormData();
data.append('SelectedFile',file);
data.append('title', title);
});
The above code makes use of .siblings() function

Deleting specific div's with JavaScript

I am trying to spawn different div's and remove them after they do their job. A simple version of my code is:
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(child);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"?\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>'
The problem is that when the first spawned div is deleted, all div's are deleted. Any help is appreciated on how to fix this.
How about something like this:
function eraseDiv(target){
var div = target.parentNode;
var container = div.parentNode;
container.removeChild(div);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<button onclick=eraseDiv(this);> Delete</button>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<button type="button" name="submit" onclick="spawnDiv();">Spawn</button>
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
First thing, since you're returning false every time you obviously don't want to use the submit functionality of your submit input, so change it to a button instead.
Second thing, remove the ID from the spawned div since you should never have two divs with the same ID.
Third thing (like the first thing) since you're not using the link functionality of the anchor element, you should change it to a button instead (using CSS you can style this like an anchor if you want to).
Fourth thing, inside the delete button, add this as a parameter to the eraseDiv function. You can now access the button that was clicked using the function parameter rather than trying to find it by an ID.
The simplest fix to your code without modifying the functionality (and view of the page) of what you did is to replace the href="?" with href="#".
In your original code, when you do something like link with the "?" as the hyperlink, this actually performs a GET request which will reload the page. This is tricky because it makes it seem like your delete code is removing all the spawned divs from both cn1 and cn2 divs.
Changing the href=? to href=# prevents a GET request from happening. Below is a snippet that directly makes this change that results in the correct behavior of your original code (by deleting the spawned element in cn1). You will have to further modify your code to make it do what you want.
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(c);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"#\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
Another way of doing it would be to create a id for div like this
<html>
<body>
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
<script>
function eraseDiv(j){
var c = document.getElementById('child'+j);
c.parentNode.removeChild(c);
}
var i=1;
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child"+i;
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<u ><a onclick=eraseDiv("+i+++"); > Delete</a></u>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
</script>
</body>
</html>

how can i access td class via jQuery?

how can i access my td class via jquery
here is HTML code
<td class="selectable" id="shoes-<?= $color->id ?>" ></td>
<td><a href="?shoes=<?php echo $color->id; ?>" title="Select"
<?php if($shoes==$order->shoes){ ?> class="selected"<?php } ?>>
Here is jQuery Code
$('td.selectable a').click(function() {
var $parent = $(this).parent();
var data = $parent.attr('id').split('-');
var type = data[0];
var typeId = data[1];
if i alert (type); i receive nothing
could you help
now i got it solved but second part still problem
I am trying to switch my class it should show up while clicking on a link here is the html code
<td class="selectable" id="person-<?= $person->id ?>">
<a href="?person=<?php echo $person->id; ?>" title="Selecteren"
if($person==$order->person){ ?> class="selected"<?php } ?>><?php echo $person->name;?></a></td>
it works with span class and div class but with a class=selected does not work
$('#personAmount td.selectable a').click(function() {
var $parent = $(this).parent()
var data = $parent.attr('id').split('-');
var type = data[0];
var typeId = data[1];
switch(type){
case 'person':
$(this).prepend('<a class="selected"></a>');
break;
case 'color':
$(this).prepend('<div class="checked"></div>');
break;
default:
$parent.prepend('<span class="checked"></span>');
}
$('td a').click(function(e) {
var id = $(this).closest('tr').find('.selectable').attr('id');
var d = id.split('-');
var item_type = d[0];
var type_id = d[1];
alert(type_id);
alert(item_type);
});
working demo
In your code, the <td> that includes the <a> doesn't have id and class attributes. The click event won't be bound to that <a>
$(this).parent().prev();
You've got a hierarchy like this:
<td class="selectable"></td>
<td>
<a>
Using your current HTML:
Live Demo
$('td.selectable + td a').click(function() {
var $parent = $(this).parent().prev();
var data = $parent.attr('id').split('-');
var type = data[0];
var typeId = data[1];
alert(type);
});

Categories

Resources