I am new to JQuery I have tried to read other solutions here in stackoverflow but I don't understand it yet. Could you please help me?
I have a button that is appended onto the page after calling a function addQuestion. When I click the button it does not work but the button with same id created in html does work.
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<div id="header">
<h1>My Site</h1>
</div>
<div id="content">
<p ><h2>Question: </h2></p>
<strong>question 1:</strong> how old am I? <br>
a) 18 <br>
b) 17 <br>
c) 22 <br>
<br>
<input id="myAnswer" type="text">
<button id="addOne">answer</button>
</div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"> </script>
<script>
$('#addOne').click(function() {
var theAnswer = $('#myAnswer').val();
alert(theAnswer);
});
function addQuestion(questionNo, task, reply){
$('#content').append("<br><br><br>" + questionNo + task + "<br>" + reply + "<br>"
+ '<input id="myAnswer" type="text">' + '<button id="addOne">answer</button>' );
}
addQuestion("<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff " );
</script>
</body>
</html>
First use classes not ID's for that button. Secondly, you need a future-proof event listener. Third, namespace your components so there is some contextual binding:
// Notice we map the answer to the button with a data attribute.
function addQuestion(id, questionNo, task, reply){
$('#content').append("<br><br><br>" + questionNo + task + "<br>" + reply + "<br>"
+ '<input id="myAnswer-' + id + '" type="text">' + '<button class="addOne" data-answer-id="myAnswer-' + id + '">answer</button>' );
}
// Notice we bind click on the static container and delegate to a dynamic element.
$('#content').on('click', '.addOne', function() {
var theAnswer = $('#' + $(this).data('answer-id')).val();
alert(theAnswer);
});
// Example add - pass in 2 for an ID
addQuestion(2, "<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff " );
Working demo : http://jsfiddle.net/x231eLc8/
as your button gets added dynamically, you need to use jQuery.on() to attach event handler to your newly created button and ID's should be unique, so make sure you use different id in case you are generating multiple buttons:
$(document).ready(function() {
$(document).on('click', '#addOne', function() {
var theAnswer = $('#myAnswer').val();
alert(theAnswer);
});
});
Hi, the problem is that you can't have two buttons with the same ID .
You can create two different buttons .. and create a new script.
<script>
$('#addOne').click(function() {var theAnswer = $('#myAnswer').val();alert(theAnswer);});
$('#addTwo').click(function() {var theAnswer = $('#myAnswer2').val();alert(theAnswer);});
function addQuestion(questionNo, task, reply){$('#content').append("<br><br><br>" + questionNo + task + "<br>" + reply + "<br>"+ '<input id="myAnswer2" type="text">' + '<button id="addTwo">answer</button>' );};
addQuestion("<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff ");
</script>
OR use classes and the "this" word.
Related
So, I have an external JavaScript that generates 4 numbers and puts them between 2 parts of text, like this
document.getElementById("gen3").textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669";
<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<div id="gen3"></div>
It generates properly and selecting it and opening it in a new tab works perfectly, but I'd like to make it easier by placing it directly into an href.
You can change your div into an a (anchor tag) in your HTML and use its href property in JavaScript to set the URL destination used when you click it. You can also choose to set its textContent to the same value, which makes it clearer to people using the tool where exactly they are going when they click the link.
gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
Demo Snippet
var gen3 = document.getElementById("gen3")
function postmessage() {
// Pretending these are "random" values, and assuming you have the code for them already
var first = 1,
fnum = 2,
snum = 3,
tnum = 4
// Later...
gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
}
<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<p>
<a id="gen3"></a>
</p>
You can create an anchor tag inside the div
Then you can do like this
JS
document.getElementById("linkText").setAttribute('href','www.google.com')
HTML
<div id="gen3">
Click Me
</div>
DEMO
I'm trying to finish my final project for my introductory web development course (I'm very new to javascript and html), which is a simple Mad Libs project. I've been running into problems all day with trying to get it to work, and I think I've largely eradicated most of the bugs. I've really hit a roadblock though, with the button I'm using that is supposed to load in the results and call the function that builds the story using an event listener in the javascript file. When I run my program, the button doesn't do a thing. I checked the Google Chrome developer console, and I'm not getting any error messages or anything, so I have no clue what I'm doing wrong.
Here's my javascript file (named mad_libs_1.js):
var story = document.querySelector("#story");
var adjective1 = document.querySelector("#adjective1");
var verbEndingInED = document.querySelector("#verbEndingInED");
var nounPlural1 = document.querySelector("#nounPlural1");
var liquid = document.querySelector("#liquid");
var nounPlural2 = document.querySelector("#nounPlural2");
var famousPerson = document.querySelector("#famousPerson");
var place = document.querySelector("#place");
var occupation = document.querySelector("#occupation");
var noun1 = document.querySelector("#noun1");
var nationality = document.querySelector("#nationality");
var femaleCelebrity = document.querySelector("#femaleCelebrity");
var noun2 = document.querySelector("#noun2");
var femaleFriend = document.querySelector("#femaleFriend");
var nounPlural3 = document.querySelector("#nounPlural3");
var number = document.querySelector("#number");
var adjective2 = document.querySelector("#adjective2");
//event listener for the button
var finished = document.querySelector("#finished");
if(finished){
finished.addEventListener("click", createStory, false);
}
function createStory(){
console.log("createStory HAS BEEN CALLED");
var finalStory = "";
finalStory += "I enjoy long, " + adjective1.bold();
finalStory += " walks on the beach, getting " + verbEndingInED.bold();
finalStory += " in the rain and serendipitous encounters with " + nounPlural1.bold();
finalStory += ". I really like piña coladas mixed with " + liquid.bold();
finalStory += ", and romantic, candle-lit " + nounPlural2.bold();
finalStory += ". I am well-read from Dr. Seuss to " + famousPerson.bold();
finalStory += ". I travel frequently, especially to " + place.bold();
finalStory += ", when I am not busy with work. (I am a " + occupation.bold();
finalStory += ".) I am looking for " + noun.bold();
finalStory += " and beauty in the form of a " + nationality.bold();
finalStory += " goddess. She should have the physique of " + femaleCelebrity.bold();
finalStory += " and the " + noun2.bold();
finalStory += " of " + femaleFriend.bold();
finalStory += ". I would prefer if she knew how to cook, clean, and wash my " + nounPlural3.bold();
finalStory += ". I know I’m not very attractive in my picture, but it was taken " + number.bold();
finalStory += " days ago, and I have since become more " + adjective2.bold() + ".";
story.innerHTML = finalStory;
console.log(story + " IS THE STORY");
}
and here's my html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>Mad Libs 1</title>
<script type="text/javascript" src="mad_libs_1.js"></script>
</head>
<body lang="en-US">
<div class="container-fluid">
<h1>Mad Libs 1</h1>
</div>
<div class="container-fluid">
<ul>
<li>Adjective: <input type="text" name="adjective1" id="adjective1"><br>
<li>Verb Ending in "ED": <input type="text" name="verbEndingInED" id="verbEndingInED"><br>
<li>Noun (Plural): <input type="text" name="nounPlural1" id="nounPlural1"><br>
<li>Liquid: <input type="text" name="liquid" id="liquid"><br>
<li>Noun (Plural): <input type="text" name="nounPlural" id="nounPlural2"><br>
<li>Famous Person: <input type="text" name="famousPerson" id="famousPerson"><br>
<li>Place: <input type="text" name="place" id="place"><br>
<li>Occupation: <input type="text" name="occupation" id="occupation"><br>
<li>Noun: <input type="text" name="noun1" id="noun1"><br>
<li>Nationality: <input type="text" name="nationaltiy" id="nationality"><br>
<li>Female Celebrity: <input type="text" name="femaleCelebrity" id="femaleCelebrity"><br>
<li>Noun: <input type="text" name="noun2" id="noun2"><br>
<li>Female Friend: <input type="text" name="femaleFriend" id="femaleFriend"><br>
<li>Noun (Plural): <input type="text" name="nounPlural3" id="nounPlural3"><br>
<li>Number: <input type="text" name="number" id="number"><br>
<li>Adjective: <input type="text" name="adjective2" id="adjective2"><br>
<button id="finished">I'M FINISHED!</button>
</ul>
</div>
<div id="story"></div>
</body>
</html>
I know that my code practices are probably sloppy--I'm just trying to get it to work before I polish it up. Also, I have to use regular javascript and no jquery. I appreciate any help I get with this because I've been working in vain for hours and hours trying to figure out what's wrong.
Further to #Jaromanda X's suggestion, try wrapping your code in a function, and then assigning that function as the window.onload event handler.
This way your code won't run until the HTML document has been loaded. Otherwise your code might run before the document has loaded and there won't be any HTML elements to operate on.
function runOnLoad() {
// all your code in here
}
// assign your function as the handler for the onload event
window.onload = runOnLoad;
You might be interested to read this question for a bit more information about how to run code after the page has loaded, and a few different ways to do it.
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You have errors in your code. bold() is not a function if you want to use bold text you can use <strong> tag.
Also if you want to get value from textbox you need to use value property.
function createStory() {
console.log("createStory HAS BEEN CALLED");
var finalStory = "";
finalStory += "I enjoy long, <strong>" + adjective1.value+ "</strong>";
story.innerHTML = finalStory;
console.log(story + " IS THE STORY");
}
I have corrected for the first textbox you can follow same for the rest.
You could use the addEventListener:
var div = document.getElementById('div');
function blah(e) {
}
div.addEventListener('click', blah);u
This would make a click event in the javascript. The e parameter is needed for this though because it calls for the event.
Im using this to capture the HTML source for a single html page.
It works good except for one thing.
After entering values into my html page, when I do the capture it only captures the page without the edited values.
Any Ideas please.
var getDocTypeAsString = function () {
var node = document.doctype;
return node ? "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>\n' : '';
};
function getPageHTML() {
// alert( "<html>" + $("html").html() + "</html>" );
console.log(getDocTypeAsString() + document.documentElement.outerHTML);
}
and the call from the button
<div class="no-print">
<div class="buttonBar">
<input type="button" class="button" value="Print" onClick="window.print()">
<input type="button" class="button" value="Save" onClick="getPageHTML()">
</div>
</div>
The editing values will come from similar fields like this
So I would like to capture the edited 'PastMedicalHistory' as-well
<div class='row'>
<div class='cell100'>
<div class='table'>
<div class='cell100 content'>
<textarea id='PMH' class='basicTextArea PMHText' name="PastMedicalHistory"></textarea>
</div>
</div>
</div>
</div>
What are you trying to achieve?
The statement document.documentElement.outerHTML will take the HTML itself as rendered.
The values of the input elements are filled in afterwards, so not visible via outerHTML.
You could run through the elements, inspect them and populate the DOM.
What would be for the best, though is to describe what are you trying to achieve and put the full code example on codepen or similar.
You can't do that, this easy way. You're getting the same as looking "source code" from your browser.
Use jQuery or JS to parse document input values.
Then reinject it in your getDocTypeAsString
Found something that seems to work fine, but Im not that great of an expert to judge this on possible limitations
keep a watch over items like this
$( document ).ready(function() {
var isDirty = false;
$("textarea").on("change", function() {
isDirty = (this.defaultValue !== this.value);
if (isDirty)
this.defaultValue = this.value;
});
$("input").on("change", function() {
isDirty = (this.defaultValue !== this.value);
if (isDirty)
this.defaultValue = this.value;
});
});
call for the source of the new html like this
function getPageHTML() {
console.log( "<html>" + $("html").html() + "</html>");
}
Hi im trying to create an edit script in jquery that changes p content to input fields, and lets people edit them and then revert back to content.
my code:
<div class="addressblock">
<div class="data">
<p name="bedrijfsnaam">company name</p>
<p name="tav">to whom</p>
<p name="adres">street and number</p>
<p name="postcode">1234AB</p>
<p name="woonplaats">city</p>
<p name="land2" >Land</p>
</div>
Edit
</div>
Jquery =
$(document).ready(function () {
$(".editinv").click(function() {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if(edit_or_text == "edit"){
$(this).closest('div').find('p').each(function(){
var el_naam = $(this).attr("name");
var el_content = $(this).text();
$(this).replaceWith( "<input type='text' name='"+el_naam+"' id='" + el_id + "' value='"+el_content+"' />" );
});
$(".editinv").replaceWith( "<a href='#_' class='editinv' name='done' id='"+editid+"'>Done</a>" );
}
if(edit_or_text == "done"){
$(this).closest('div').find('input').each(function(){
var el_naam = $(this).attr("name");
var el_content = $(this).attr("value");
$(this).replaceWith( "<p name='"+el_naam+"' id='" + el_id + "'>'"+el_content+"' </p>" );
});
$(".editinv").replaceWith( "<a href='#_' class='editinv' name='edit' id='"+editid+"'>Bewerken</a>" );
}
});
});
When clicking on edit it changes perfectly to input fields and changes the edit button to a done button. A click on the done button is never registered though, while the class is the same.
Anyone got any ideas?
Thanks in advance!
EDIT: I created a JSfiddle of the problem http://jsfiddle.net/hBJ5a/
ITs quite simple, why doesn't the element accept a second click and revert back after already being changed?
Note that if you change the name of all the <p> tags to the same name, and try to revert them back, there is no way that javascript will know which value should go where.
You should add an additional parameter to your <p> tags that will indicate the type.
e.g.
<p data-type="text" name="bedrijfsnaam">compname</p>
when changed will turn into:
<input type="text" name="bedrijfsnaam" data-type="edit" value="compname" />
when you click the button to change back, you should simply use the same function you are currently using to change the <p>'s into <input>'s, but then reverse the order.
e.g.
function inputToParagraph() {
var inputs = $('input[data-type="edit"]');
inputs.each(function() {
$(this).replaceWith('<p data-type="text" name="'+$(this).attr('name')+'">'+$(this).attr('value')+'</p>');
});
}
ofcourse you should have other actions linked to your submit, an ajax request probably to update the database as well.
NOTE
Not tested, but do know that the function above, if all the attr's are specified will work.
It will directly replace the inputs with P tags with given attributes.
You will have to make sure when you make the <p>'s into <input>'s, you will have to make sure the inputs get the correct attributes as well.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var clickHandler = function() {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function() {
var el_id = $(this).attr("id");
var el_naam = el_id; //$(this).attr("name");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editinv").replaceWith("<a href='#_' class='editinv' name='done' id='" + editid + "'>Done</a>");
}
else /* if (edit_or_text == "done") */ {
$(this).closest('div').find('input').each(function() {
var el_id = $(this).attr("id");
//var el_naam = el_$(this).attr("name");
var el_content = document.getElementById(el_id).value;
// Attribute "name" not allowed on element "p" at this point
//$(this).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>'" + el_content + "' </p>");
$(this).replaceWith("<p id='" + el_id + "'>" + el_content + "</p>");
});
$(".editinv").replaceWith("<a href='#_' class='editinv' name='edit' id='" + editid + "'>Bewerken</a>");
}
document.getElementById("00001").onclick = clickHandler;
}
$(document).ready(function() {
document.getElementById("00001").onclick = clickHandler;
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div class="addressblock">
<div class="data">
<!-- Attribute "name" not allowed on element "p" at this point -->
<p id="bedrijfsnaam">company name</p>
<p id="tav">to whom</p>
<p id="adres">street and number</p>
<p id="postcode">1234AB</p>
<p id="woonplaats">city</p>
<p id="land2">Land</p>
</div>
Edit
</div>
</body>
</html>
Tested with Firefox 24.0 / Linux
try out jquery editable plugin
demo: http://www.appelsiini.net/projects/jeditable/default.html
I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);