Find and replace an element in html using jquery - javascript

I am trying to load a HTML page into a variable in Jquery, then replace a div element tag in it, so I can get my own id into the div. I am using this way to dynamically add more users in my web app, and then do a batch POST to the back end, and put the info into json.
Here is my html that I am loading.
info.html
<div id="user">
<label>name</label>
<input type="text" name="name">
<br>
<label>email</label>
<input type="text" name="email">
<br>
</div>
I load this with jquery and I want to replace <div id="user"> with something
like <div id="user 1">
I have the following jquery script that has a counter to keep track of what number to append onto the div tag.
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
var content = $('<div>').load("static/info.html"); //using python flask
console.log(typeof(content)); //is of object type
console.log(typeof(content.html())); //is of type string
console.log(content.html());//shows up as an empty string
console.log(content);//prints out the object
content = content.html().replace('<div id="user ">','<div id="user "'+counter+'>'); // doesn't work.
$("#add_div").append(content); //appends correctly if I remove the above line, but all divs have the some id.
});
});
Any suggestions would be great thanks. Also, is the is the best way going about keeping track of how many times a new user is added(as in using a counter and keep track of how they are added, and then do the same when I click submit and create the json)?

.load() is asynchronous. make your changes in side callback.
.load("..",function(){
// your changes
});
Also $( "selector" ).load() is the syntax. So create a div and load content to it.
// modified code structure
<div id"content"></div>
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
$("#content").load("static/info.html",function(){
content = $("#content").html().replace('<div id="user ">','<div id="user "'+counter+'>');
$("#add_div").append(content);
}); //using python flask
});
});

Using JavaScript, you can use the .attr() method to target id, then set its value like so:
$("#content").attr("id", "user_" + counter);

Try an $.each() function for #user like this:
$('#user').each(function(indexNumber){
$(this).replace('<div id="user'+indexNumber+'"></div>');
});

Related

How can I loop through a jquery array and then output each item (starting at index 0) one at a time?

I'm trying to collect user responses and add them into the answers array. Then I want to display the most recent user input (answers[0]) into the .user-answer div. I've managed to get that part taken care of but if you see a better way to do it then please show me.
The second part of is that I want to show the items in the array one at a time in the .dynamic-content h2 slot. I need to loop through the array (starting at answers[0]), pull out each item, show it in the div and then move to the next item and show it in the div.
Here's a link to the CodePen.
HTML
<div class="answer">
<h1>Life, Liberty, and </h1>
</div>
<div class="user-answer">
<h1>_________</h1>
</div>
<input type="text"/>
<input type="submit"/>
<div class="dynamic-content">
<h1>What is your pursuit of happiness?</h1>
<h2>Output array items here</h2>
</div>
JavaScript
// create an empty array
var answers = [];
// STORE AND OUTPUT DATA ON SUBMISSION
function handleUserInput() {
// store user input
var userInput = $('input[type=text]').val();
// append input value to answers array
answers.unshift(userInput);
// add latest user input into the HTML
$('.user-answer').html('<h1>' + answers[0] + '</h1>');
}
// RUN FUNCTION ON SUBMISSION
$('input[type=submit]').on('click', function() {
handleUserInput();
});
It's not the best way but here it goes. This method is like you asked to change the SAME DIV dynamically, so no other items are created, they just "change"
Add this function:
function rotateTerm() {
if(answers.length>0){
var ct = $("#rotate").data("term") || 0;
$("#rotate").data("term", ct == answers.length -1 ? 0 : ct + 1).text(answers[ct]).fadeIn().delay(2000).fadeOut(200,function(){
rotateTerm();
});
}
}
$(rotateTerm);
Then in your submission put:
$('input[type=submit]').on('click', function() {
handleUserInput();
$(rotateTerm);
});
working CodePen thanks to Nick Craver's answer in this thread.
Just change your JS a little bit to this:
var answers = []; // create an empty array
// STORE DATA ON SUBMISSION
function handleUserInput() {
var userInput = $('input[type=text]').val();
$('.user-answer').html('<h1>' + userInput + '</h1>');
answers.push(userInput);
$('.dynamic-content h2').html(answers + ', ');
}
$('input[type=submit]').on('click', function() {
handleUserInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="answer">
<h1>Life, Liberty, and </h1>
</div>
<div class="user-answer">
<h1>_________</h1>
</div>
<input type="text"/>
<input type="submit"/>
<div class="dynamic-content">
<h1>What is your pursuit of happiness?</h1>
<h2>Output array items here</h2>
</div>
First, I don't know if you want to do this on server side or in client side, but for server side you need to make it work with a server side scripting language, like PHP, or Perl. For clent side, you need to cancel the default submit event when user clicks the submit button, else the page will refresh posting the form data.
So, to do this without the page refreshing, first add the event to the onclick event and pass it to your handleUserInput function like this:
$('input[type=submit]').on('click', function(e) {
handleUserInput(e);
rotate();
});
then, cancel the event by using preventDefault to the event object:
e.preventDefault();
now, to display the data to .dynamic-content and add the answers in h2 tags, you first need to remove all h2 elements (because you already have an h2 element there, or you could also prepend if you remove the h2 Output array items here tag) and then add all the answers starting from the first one like this:
$('.dynamic-content h2').remove();
$.each(answers, function(i, v) {
$('.dynamic-content').append($('<h2/>').text(v));
});
The final code will be something like this:
var answers = []; // create an empty array
// STORE DATA ON SUBMISSION
function handleUserInput(e) {
e.preventDefault();
var userInput = $('input[type=text]').val(); // store user input
answers.unshift(userInput); // append value to answers array
// $('.user-answer').fadeIn().html('<h1>' + answers[0] + '</h1>').delay( 500 ).fadeOut(); // add user input into the HTML
$('.user-answer').html('<h1>' + answers[0] + '</h1>'); // add user input into the HTML
$('.dynamic-content h2').remove();
$.each(answers, function(i, v) {
$('.dynamic-content').append($('<h2/>').text(v));
});
// $('.answer').html('<h1>' + answers[0] + '</h1>');
// $.each(answers[0 + i], function() {
// $('.answer').fadeIn().html('<h1>' + answers + '</h1>').delay( 500 ).fadeOut();
// });
}
$('input[type=submit]').on('click', function(e) {
handleUserInput(e);
rotate();
});
http://codepen.io/clytras/pen/zoBXpE

javascript that can access element declared in a variable

List item
i want a javascript that can access the button elements inside
the
dot.append() function. so that when i clicked the button i
get the value of that button.
below is a piece of code that have been working on this morning.
i appreciate any support or hint from anyone.Thank you in
advance.
further more i am also new in youtube data api.
function main_search(){
$("form").on("submit",function(e){
e.preventDefault();
//after that we prepare the request
var myRequest = gapi.client.youtube.search.list({
part: 'snippet',
q: encodeURIComponent($("#query").val()).replace(/%20/g, "+"),
maxResults :5,
type : 'video'
});
// then we execute the request
myRequest.execute(function(response){
var results = response.result;
$.each(results.items, function(index,item){
$("#results").append('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
});
});
});
}
function loadAPI(){
gapi.client.setApiKey("AIzaSyC1CJHONRDvyfSS3xAOG9SfW_VCXMoLK5Y");
gapi.client.load("youtube","v3", function(){
//my youtube api is read
main_search();
});
}
<form action="#">
<input type="search" id="search_string" placeholder="Your string
goes
here...."></input>
<input type="submit" name="search-btn" id="search_btn" value="search">
</input>
</form>
<ul id="result_box"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script src="search.js"></script>
Just divide your statement into two lines so that you can access the element later:
var element = document.createElement('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
$("#results").append(element);
Or if you want a jQuery object instead:
var element = $('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
You can then access whatever you want from the element variable.
Alternatively you can just grab the button later using the class if you keep your current code:
var button = $('.class_btns');

A HTML tag to store "javascript's data"?

I need to write some html with placeholder used for javascript.
ex:
<span><placeholder data-id="42" data-value="abc"/><span>
Later on, a script will access those placeholders and put content in (next to?) them.
<span><placeholder data-id="42" data-value="abc"><div class="Google"><input type="text" value="abc"/></div><span>
But the placeholder tag doesn't exist. What tag can be used? Using < input type="hidden" .../> all over feels wrong.
Creating Custom tag
var xFoo = document.createElement('placeholder');
xFoo.innerHTML = "TEST";
document.body.appendChild(xFoo);
Output:
<placeholder>TEST</placeholder>
DEMO
Note: However creating hidden input fields with unique ID is good practice.
give your span element an id like,
<span id="placeToAddItem"><span>
and then in jQuery,
$('#placeToAddItem').html('<div class="Google"><input type="text" value="abc"/></div>');
or else
var cloneDiv = $('.Google');
$('#placeToAddItem').html(cloneDiv);
Example
The best way to do this, is using <input type='hidden' id="someId" value=""> tags.
Then you can easily access them by using jQuery, and recall the variable or change it.
var value = $("#someId").val(); to get variable or $("#someId").val(value) to change it.
This complete, no jQuery solution allows you to specify the placeholder/replacement html as a string within the element that will be replaced.
EG HTML:
<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>
<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>
<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>
<span data-placeholder="<em>Post JS</em>">Pre JS</span>
<br />
<button id="test">click me</button>
JS:
Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)
var placeholders = document.querySelectorAll('[data-placeholder]'); //or by ids, classnames, element type etc
Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list.
NodeList.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i]);
}
return this;//return self to maintain chainability
};
Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string:
Object.prototype.replaceWith = function(htmlString) {
var temp = document.createElement('div');//create a temporary element
temp.innerHTML = htmlString;//set its innerHTML to htmlString
var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
this.parentNode.replaceChild(newChild, this);//replace old node with new
return this;//return self to maintain chainability
};
Put it all together:
placeholders.each(function(self){
self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});
Another example but here we only replace one specific element with some hard-coded html on click:
document.getElementById("test").addEventListener('click', function() {
this.replaceWith("<strong>i was a button before</strong>");
}, false);
DEMO: http://jsfiddle.net/sjbnn68e/
use the code below :
var x = document.createElement('placeholder');
x.innerHTML = "example";
document.body.appendChild(x);

Replace text, and replace it back

I am using this code to replace text on a page when a user clicks the link. I would like a way to replace it back to the initial text using another link within the replaced text, without having to reload the page. I tried simply adding the same script within the replaced text and switching 'place' and 'rep_place' but it didn't work. Any ideas? I am sort of a novice at coding so thanks for any advice.
<div id="place">
Initial text here
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</div></span>
Where do you store the original text? Consider what you're doing in some simpler code...
a = 123;
b = 456;
a = b;
// now how do you get the original value of "a"?
You need to store that value somewhere:
a = 123;
b = 456;
temp = a;
a = b;
// to reset "a", set it to "temp"
So in your case, you need to store that content somewhere. It looks like the "source" is a hidden element, it can just as easily hold the replaced value. That way values are swapped, not just copied. Something like this:
function replaceContentInContainer(target,source) {
var temp = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
document.getElementById(source).innerHTML = temp;
}
So replace them you simply call:
replaceContentInContainer('place', 'rep_place')
Then to swap them back:
replaceContentInContainer('rep_place', 'place')
Note that this will replace the contents of the "source" element until they're swapped back again. From the current code we can't know if that will affect anything else on the page. If so, you might use a different element to store the original values. That could get complex quickly if you have a lot of values that you need to store.
How's this? I store the initial content in an element of an array called initialContent.
<div id="place">
Initial text here [replace]
</div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here [revert]
</span>
</div>
<SCRIPT LANGUAGE="JavaScript">
var initialContent = [];
function replaceContentInContainer(target,source) {
initialContent[target] = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function showInitialContent(target) {
document.getElementById(target).innerHTML = initialContent[target];
}
</SCRIPT>
Working example: http://jsbin.com/huxodire/1/
The main changes I did were the following:
I used textContent instead of innerHTML because the later replaces the whole DOM contents and that includes removing your link to replace the text. There was no way to generate that event afterwards.
I closed the first div or else all the text would be removed with the innerText including the text that works as a link.
You said you wanted to replace back to the original text, so I used a variable to hold the last value only if this existed.
Hope this helps, let me know if you need more assistance.
The div tags were mixed up and wiping out your link after running it. I just worked with your code and showed how you could switch.
<div id="place">
Initial text here
</div>
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML =
document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div>
<div class="text" onClick="replaceContentInContainer('place', 'original_place')">
<u>Link to restore text</u></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</span>
<span id="original_place">
Initial text here
</span>
</div>

How to get text field value from another page javascript

Here My script code
page 1 / index.php
$(document).ready(function(){
$("#list").load("load_list.php");
function reloadlist(){
var total_list = $("#total").val();
$.get('load_list.php', function(data){
var values = $("input[name='total']", data).val();
alert(values);
});
} setInterval(reloadlist, 3000);
})
<body>
<div id="list"></div>
</body>
page 2 / load_list.php
[My query for get the total data]
<input type="hidden" name="total" id="total" value="<?=$total?>">
When i load that index page, and alert value will be undefined. how to get text field value from load_list.php
save the value in a cookie and retrive it in next page
The element is at root level, and the contex selector uses find() internally, and that only works on descendants.
You can avoid any and all issues with elements being descendants or at root level by appending the content to another element, and then using find(), or you could use filter() directly
$.get('load_list.php', function(data){
var values = $('<div />', {html: data}).find("input[name='total']").val();
alert(values);
});
Also, the element has an ID, and it would be more efficient to use that in the selector.
You're in kind of a bad situation since you're just reloading the list after 3 seconds even if the call failed. You should try to clean up the whole idea a bit.
function reloadList = setTimeout(function(){
$.get('load_list.php', function(result){
var value = $(data).filter('#total').val();
alert(value);
reloadList();
});
}, 3000);
reloadList();

Categories