javascript set variable from .text method - javascript

I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks

Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"

Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

Related

How to set a textbox to an eval() in javascript

Okay, so I am trying to make a quiz where you enter some code and the quiz executes the code to see if what you typed is the same as the answer.
Here is the code and this is how the webpage looks like:
questions = "PRINT HELLO"
document.getElementById("Question").innerHTML = questions
function check(){
document.getElementById("answertext").innerHTML = eval(document.getElementById("answerbox").value)
}
#answerbox{
width:100%;
height:500px;
font-size:25px;
}
<h1>QUIZZZ</h1>
<h2 id = Question>JAVASCRIPT CONSOLE AND EXERCISES</h1>
<h1 id = "hi"></h1>
<textarea rows="4" cols="50" id = "answerbox">
//put your answer here
</textarea>
<textarea rows= '4' cols = "50" id = "answertext">lol</h1>
</textarea>
<input type = "submit" onclick = "check()">
Run the code to see
I want the user to enter a document.write() statement inside the textbox, and have the evaluated code to be shown in the smaller multiline text box.
Try to put a document.write() statement in the textbox and run it. You should see a new page instead of the answer written in the text box.
I know that document.write is a bad practice to output things in javascript, and I know that you can edit raw HTML, but is there any other way a user can print a message without doing any of these choices?
Don't use eval.
Using eval is considered to be a bad practice. Read more for Why here. You can ask your user to just return the answer using a return statement as shown below, instead of asking them to do something complicated like document.write().
// Ask them to do this:
var codeFromTheAnswerBox = "var answer = 'HELLO'; return answer;"
// instead of this:
// var codeFromTheAnswerBox = "var answer = 'HELLO'; document.write(answer)";
// execute user's code
var code = new Function(codeFromTheAnswerBox);
var returnValue = code();
// Now do whatever you want to do with the answer like the following
alert("Your answer is " + returnValue);
You can use .append instead of document.write()
document.body.append("Hello World!", document.createElement('p'));
If you go to the Console tab of the DevTools in your browser, you can type javascript code and press enter to execute it. You will get helpful error messages that should help you with your project.
Ok. I realized your problem.
You can use iframe for this purpose. Add an iframe with an id similar 'answerIframe' instead of #answertext element.
Then move your #answertext element to a separated html and set address of iframe to it.
In iframe:
window.check=function(){
document.getElementById("answertext").innerHTML =
eval(document.answer);
}
And add a button to your iframe too. for iframe's button set this:
onclick="window.check()"
Add an Id to iframe's button similar: iframe_bt.
Now, when user clicks on button (in current page, no iframe) must call this (new check function in your main page):
function check(){
document.getElementById('#answerIframe').contentWindow.document.answer=document.getElementById("answerbox").value;
document.getElementById('#answerIframe').contentWindow.document.getElementById('#iframe_bt').click();
}
Also in your iframe, call a function in document's onload and add answertext dynamically if is not exists (because document.write) or reset the iframe before execute per answer.
Another way is replacing the document.write with other code similar: elem.insertAdjacentHtml(..) or etc before execute it.
Excuse me for any mistake, i typed with my cellphone.
I did not have a tool to test it, but the method and its generalities are correct.

editing html with embedded PHP using javascript

I hope someone has an answer for me,
I am currently trying to create a PHP product page for my shop website, I have an sql table that stores the name of an image prefix eg if the image file is 'test_1.png' then the table stores 'test'. using embedded php
src="images/shop/<?php echo $row['item_img'], '_1.png';?>"></img>
what I would like to do is using js, dynamically update the src on a mouse click.
something like eg.
var imgSwitch = function(i){
Document.getElementById('js-img').src = "images/shop/
<?php echo $row['item_img'], '_';?>i<?php echo '.png';?>";
}
Even to me this seems wrong which is why I've turned to the GURU's here
Is there anyway this would be possible? If not, any suggestions would be GREATLY appreciated
I am trying to figure out what you are asking, and I think this is your way to go:
var imgSwitch = function(i){
document.getElementById('js-img').src = "images/shop/<?php echo $row['item_img'], '_';?>" + i + ".png";
}
The change is in the i, you have to cut the string and add it as a variable.
But remember that the PHP code is executed at the server, and will not change once the page is sent to the client. When you execute that function, $row['item_img'] will always be the same.
A simple example which you can adapt. What I do in the code below is give the element an id and attach an onclick to it.
In the function we pass the id as a parameter (onclick(changeSrc(this.id))) and we manipulate the src using the getElementById as we have the id.
<img src="http://ladiesloot.com/wp-content/uploads/2015/05/smiley-face-1-4-15.png" id="test" onclick="changeSrc(this.id);" height="400" width="400" />
<script>
function changeSrc(id) {
document.getElementById(id).src = "http://i0.wp.com/www.compusurf.es/wordpress/wp-content/uploads/2014/04/smiley.jpeg?fit=1200%2C1200";
}
</script>
http://jsfiddle.net/tq1Lq5at/
Edit 1
You're using Document when it should be document, notice the lowercase d.

JS - Dynamic Href Change

Ive tried many way but im new to JS, I mainly do PHP.
Anyway the code:
<script>
var userinput = $('input[name="imdbid"]');
userinput.change(
function(){
$('#userimdb').attr('href')+$('input[name="imdbid"]').val();
}
);
</script>
Basically, the imdbid is gotten from a input tag, basically I want to append whatever the user types to a href of a tag, This doesnt seem to work doe. When I alert() it, it seems to give me the output of what its meant to but when I remove alert() it doesnt seem to change the href, I also tried .setAttribute() but that also just did nothing.
Please help me out im going insane right now.
Try this:
You need to assign it to href attribute..
var userimdb=$('#userimdb');
var baseURL=userimdb.attr('href');
$('input[name="imdbid"]').change(function()
{
var userimdb=$('#userimdb');
userimdb.attr('href', baseURL + $(this).val());
});
You're not setting the attribute right now, only accessing it. In addition, you need to store the original href attribute somewhere so you're not adding the same text repeatedly. Here's the updated code:
var userinput = $('input[name="imdbid"]');
var orighref = $('#userimdb').attr('href');
userinput.change(function(){
$('#userimdb').attr('href', orighref + userinput.val());
});

How to save an image's attribute id to a variable?

UPDATE - Sorry I tried to keep the code minimal, but looks like more detail is needed. I've created a non production jfiddle here with some notes to help explain what I'm trying to solve.
Hopefully this provides you with all details
http://jsfiddle.net/d86tm/5/
From looking at Google and SO nothing quite answers my answer...
After a user clicks an image I'd like to capture the attribute id assigned to the image and save it within a variable, something like
var friendRequestId = $(e.source).data("UserForBadge");
At the moment I have. But I'm not certain this is correct and its certainly returning an error
Uncaught ReferenceError: friendRequestId is not defined
Just looking for guidance/best practice example on how to complete this.
$(document).ready(function() {
$('.UserForBadge').css('cursor', 'pointer');
$('.UserForBadge').click(function(e) {
$(this).appendTo('friendRequestId');
// Nothing to worry about this part at the mo/////////
return false;
});
});
From what I understood by the question you wanted the id on the click of the image using jquery. Please find the fiddle
The code snippet used is:
e.target.id
if i understood correctly. your markup should be:
<img id="someId" onclick="imgClick(this)" />
and your js function:
function imgClick(sender){
var $img = $(this); //creates jQuery object from the DOM object
var id = $img.attr('id'); // extracts the id attribute
//your code...
}

Deleting and inserting Code in a DIV via jQuery

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)
If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");
.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);
I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

Categories

Resources