I have javascript in page One :
<script>
var valueRm = noRm.value;
localStorage.setItem("noRm", valueRm);
</script>
And this is my javascript in second page :
<input id="noRmUser" name="noRmUser"/>
<script>
var valueRm = localStorage.noRm;
//i try with 3 ways, but i can't get that value
//-->> document.getElementById('noRmUser').value = valueRm;
//-->> document.getElementById('noRmUser').setAttribute('value',
localStorage.getItem('noRm'));
//-->> document.getElementById('noRmUser').setAttribute('value',
localStorage.getItem('valueRm'));
//but if i show in console, that value can show
//-->> console.log(valueRm);
i want show noRm from page one and show noRm in second page on tag input...
I start to learn javascript.. Can someone help me?
Very thankyou if someone want to help me :))
Your script must come after the input. Page rendering stops when a script tag is encountered and the JavaScript runs immediately.
There is no element in the dom when the script tries to assign it.
Put the script at the bottom of the page, right before the closing body tag
Jsfiddle
Before set some value in input.value .
<input id="noRmUser" name="noRmUser" value="hello"/>
For first thing element call was wrong
use
var valueRm = document.getElementById('noRmUser').value;
And localStorage.noRm; is one invalid call .get item only use localStorage.getItem('noRm')
For Page 1 : dont forget to add value="something" in input element
var valueRm = document.getElementById('noRmUser').value;
localStorage.setItem("noRm", valueRm);
For second Page 2
window.onload = function(){
document.getElementById('noRmUser').value =localStorage.getItem('noRm')
}
Related
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.
We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.
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;
I am trying to show a div element on a specific page e.g. - example.com/my-account , right now it is showing on all my-account pages for example - example.com/my-account/lost-password
I know how to use JavaScript but not in webpages so can someone help me? This is how I would do it with JavaScript. I just need someone to help get this to work inside the php page I am trying to edit.
<script>
var cx = window.location;
var curWin = String(cx);
var myAccount = "http://example.com/my-account/";
if (curWin == myAccount){
<div id="banner"><img src="http://img.c5454o.png"></div>
}
</script>
If you open your developer tool, you can see that the body is assigned with classes (when using <body <?php body_class(); ?>>).
For example <body class="home page page-id-7 page-template-default">.
So from here on, you can tell css what to do like so:
#banner {display: none;}
body.page-id-7 #banner {display: block;}
So you don't realy need Javascript to detect a specific page and display a specific element.
Add Your condition like this
var cx = window.location;
if(cx.substr(-11)=="my-account/") {
//then do whatever you want
}
OR if your string is without last slash then..
if(cx.substr(-10)=="my-account") {
//then do whatever you want
}
substr(-11) function will cut your string of url from last 10 indexes so
you can apply your contion then.
if you want to show a div element on specific page then create a unique id on that page like <div id='UniqueId'> then go to javascript code and write,
jQuery Code is:
if($('#UniqueId').length > 0)
{
//show specific element
}
How would you select the first input in the code below without editing the DOM (using jQuery if needed)?
<input type="text"/> <!-- The element I want to select -->
<script>
// Select the input above
</script>
<input type="text"/>
Please note there is an unknown number of inputs and script tags before and after this code sample, thus solutions like $("input:eq(1)") won't work.
The tricky part is to select the input placed right before the script tag from which the current JavaScript is being executed.
No need to ask me why I want to do this either, that's purely for the beauty of it, I want to do it without having to add random ids to my inputs if that's possible.
Edit
Here's why most of the answers won't work: http://jsfiddle.net/2WqfP/
Scripts are always run as they are loaded, so the <script> tag that's running will always be the last one on the page. With pure JS you can get it like this:
var scripts = document.getElementsByTagName('script'),
currentScript = scripts[scripts.length - 1];
Edit: I got this wrong before. To get the input at this point, you want to get the preceding sibling, so you'd use previousSibling. Also, see thesystem's comment below about text nodes and a potential solution.
var scripts = document.getElementsByTagName('script'),
currentScript = scripts[scripts.length - 1],
input = currentScript.previousSibling;
You could also use jQuery:
var currentScript = $('script').last();
Once you have the script, you can get the preceding input easily:
var input = $('script').last().prev();
Here's a jsfiddle showing my solution.
$("input:last").val("test");
This works because when the script is reached, the input immediately preceding it is the last input to be created - the following <input>'s have not yet been added to the DOM. If you ran the code after page load (that is, in an onload even handler), this wouldn't work.
It's worth noting that I would personally prefer ids, so that you don't rely on inline JavaScript (which is usually a bad idea).
Inline scripts are always run as they are parsed and the < script > tag only sees what above of him.
Best solution on pure JS:
<input type="text"/> <!-- The element I want to select -->
<script>
var inputs = document.querySelectorAll('input');
var above_input = inputs[inputs.length - 1];
</script>
<input type="text"/>
Try this:
$("script").prev("input");
Have you tried something like this?
var input = $('script').prev();
http://api.jquery.com/prev/
Native DOM solution:
var all = document.getElementsByTagName("*");
var input = all[all.length - 2];
The script will be the last element on the page when it runs, so the input will be second to last.