How do you set a permanent value in jQuery - javascript

I want to set a permanent value to a div element with jQuery;
the full js file:
$(function () {
var $a;
var $b;
$('button').click(function () {
$a = $('#a').val();
$b = $('#b').val();
var $big = getBigger($b, $a);
var $small = getSmaller($b, $a);
$('#bigger').text($big);
$('#smaller').text($small);
});
});
//a simple function for getting a bigger element
function getBigger(a, b) {
return a ^ (a ^ b) & -(a < b);
}
//a simple function for getting a smaller element
function getSmaller(a, b) {
return (a < b) ? a : b;
}
the full html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style/style.css">
<title>Compare</title>
</head>
<body>
<form>
Enter a: <input type="number" id="a"><br/>
Enter b: <input type="number" id="b"><br/>
<button> Compare</button>
<div id="bigger"></div>
<div id="smaller"> </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The problem is that when I leave the scope the variable gets destroyed
PS. Now I realise that my mistake is that when a <button> is added in a form element, everytime the button is pressed, the data in the form gets reseted

When you run code within a function it creates a scope. Each variable you define using the var statement will be available only in that scope.
To create a variable for usage outside of the current scope, either declare a variable without putting var beforehand or directly write window.varname = value. Have another read on that topic.
Besides that, in your code $('#bigger').text($big); the var $big never even gets defined, so maybe that is the problem.
And setting an elements text works independent from scopes or variables.

Try this
To Access:
$("#a").data('value');
To Set
$("#a").data('value' , 'whatevervalue');
To Access Without JQuery:
document.getElementById("a").dataset.value;
To Set Without JQuery;
document.getElementById("a").dataset.value = "Some Value";
A Div cannot hold the Value attribute unless you use:
document.getElementById("a").setAttribute("value" , "val");
Then to Assign it to Inside your div:
$("#myDivElement").html($("#a").data('value'))

Related

I want to assign one variable twice but only want to use first one in javascript

There is a file name vicidial.php in vicidia file a value is assigned
var DiaLControl_auto_HTML = 'something'
I dont want to edit in this file but i want to edit this variable from other file so i created file_js.js but when i assigned var DiaLControl_auto_HTML = 'my_value' its only use first one eg. something i want to override my variable. how can i do this ?
<script src="file_js.js"></script>
in vicidial.php
var DiaLControl_auto_HTML = 'default value';
in file_js.js
var DiaLControl_auto_HTML = 'my_value';
In vicidial have:
<script>
var DiaLControl_auto_HTML = 'default value';
</script>
<script src="file_js.js"></script>
in file_js.js
window.addEventListener("load",function() {
window.DiaLControl_auto_HTML = 'my_value';
})
this is a workable code , try it. I hope it can help you.
main html
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Test Var</title>
<script src="file_js.js"></script>
</head>
<body>
<br>
Value before : <span id="valueBefore"></span><br>
<br>
Value after : <span id="valueAfter"></span><br>
<br>
<script>
var DiaLControl_auto_HTML="default value";
// the function() wil be executed when your page is loaded
// better use readystate==complete, but it is a another problem...
window.addEventListener("load",function() {
// set var
DiaLControl_auto_HTML = 'my_value';
// show it in browser
document.getElementById('valueBefore').innerHTML=DiaLControl_auto_HTML;
// call method on file_js
myOwnFunction();
// show it in browser
document.getElementById('valueAfter').innerHTML=DiaLControl_auto_HTML;
})
</script>
</body>
</html>
file_js.js
// file_js.js FILE
function myOwnFunction () {
DiaLControl_auto_HTML="Value changed";
}

Why does this JavaScript/jQuery functionality work - undeclared variable [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 4 years ago.
If I try to declare s as a variable it errors out. It is acting like s isn't a variable and really doesn't like any changes to the syntax at all.
I've actually written a decision tree webpage that relies on this concept a lot and I'm not sure why it works.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
A variable is undeclared when it does not use the var keyword. It gets created on the global object (that is, the window), thus it operates in a different space as the declared variables.
Find out more on this link
Variables that are assigned without var keyword are called undeclared. These are created in the global scope. So your s variable is available in the click handler.
Now this only happens in non-strict mode, so if you put 'use strict' directive inside or above the selection function you'll get an error.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
'use strict'
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
Setting your s like this:
function selection(select){
s = select;
}
is similar (for variable scope) to:
var s;
function selection(select) {
s = select;
}
So s exists as a property of window, and available both inside of selection function and for alert("boop " + s);, because window is a global object. But if you declare and assign a value to variable with var inside a function:
function selection(select) {
var s = select;
}
s will have only a scope of function selection, and retrieving it here:
alert("boop " + s);
causes an error, because it doesn't exist here.

At first it said its not a function, now its just not doing anything

Okay, I'm trying to make a cheesy accent generator to practice with RegEx. But I have a strange problem that seems unrelated to RegEx. The submit button doesn't do anything. At first the function "maccent" was just called "accent" and at that time the console said "accent" was not a function. With nothing better to go on, I assumed it was because the word "accent" was used so many other times, so I changed the function name to "maccent". Now, however, nothing happens. What's the deal? Here is my code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p>Choose an accent</p>
<input type = "text">
<form action="">
<input type="radio" name="accent" value="German"> German<br>
<input type="radio" name="accent" value="English"> English<br>
<input type="radio" name="accent" value="Indian"> Indian
</form>
<button type="submit" onclick = "maccent()">Submit</button>
<div id = "accented"></div>
<script>
var accent = $('input[name="accent"]:checked').val();
function maccent()
{
if (accent == "German")
{
germAcc();
}
}
function germAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word
var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what? It replaces t even if its not followed by h
var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);
}
function indAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word
//this words, but not on each indivual word
console.log(desire);
}
function itAcc()
{
}
function britAcc()
{
var sample = $("input").val();
var desire = sample.replace(/[a]/gi, "au")
var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one
console.log(desire2);
//not if it's at the end of a word
}
</script>
</body>
</html>
The problem is the assignment of the "variable" accent. You are doing it at global scope (the top level), so it gets assigned when the page is first loaded.
If you move that assignment into the function maccent() (and move the work "mark" back into the comment it belongs to), your page will work.
Incidentally, the old problem was that you had a function and a variable trying to share the name accent. The variable was "winning".

Trouble Getting HTML Input Into JS

So, I'm trying to build a decimal to binary converter for my computer science class. I already made an algorithm in Python that seems to be working pretty well. It works in the Javascript console perfectly fine too. I'm now at a point trying to accept input from an HTML form. I'm kind of a DOM noob, but I thought this would be something easy and fun to do, but it's turning out that it's a lot more confusing than I thought. I would know how to do this in React.js, but I'm trying to use this as a learning experience. Basically, I want to take input from a form, run it through a function and have the returned value of the function back into HTML. I know how to get the value into HTML, but I have no clue how to retrieve the form data into Javascript. Here's a Codepen with my progress so far.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Binary Calculator</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<center><form style="margin-top: 25%" id="myForm">
<input type="text" class="form-control" style="width: 250px" placeholder="Type a number!" id="textForm">
<br />
<input type="button" class="btn" style="margin-top: 15px" value="Submit">
</form></center>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function conversion(){
var quotient = 15;
var convertedNum = [];
if (formValue == 0){
convertedNum = [0]
}
while(formValue >= 1){
quotient = formValue/2;
var mod = formValue %2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
console.log(convertedNum.join(""));
}
$('#textForm').change(function(){
var formValue = document.getElementById('#textForm').value;
parseInt(formValue);
console.log(formValue);
console.log("It's Working in Console!");
conversion();
});
Her's a simple way doing what you are trying to accomplish.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<body>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You want to put the answer back onto the page to be displayed when they click submit?
First you'll need a container (well, you can create one on the fly in Javascript, but typically you would just create an empty div container to hold the answer).
Add a div container for the solution: (after form probably)
<div id="convertedToBinary" class="answerDiv"></div>
It looks like you're using jQuery, which makes entering HTML into a target easy.
Add this to your conversion function:
$('#convertedToBinary').html(formValue+" converted to binary is: "+convertedNum.join("") );
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="form-control" />
<span id="result"></span>
<script>
var formValue;
function conversion()
{
var quotient = 15;
var convertedNum = [];
if (formValue == 0)
{
convertedNum = [0]
}
while (formValue >= 1)
{
quotient = parseInt(formValue / 2);
var mod = formValue % 2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
$('#result').html(convertedNum.join(""));
}
$('.form-control').keydown(function ()
{
var $this = $(this);
setTimeout(function ()
{
formValue = $this.val();
conversion();
}, 100);
});
</script>
</body>
</html>
Just a couple of hints starting from the HTML / JS you provided:
You are using a jQuery selector within plain JS, so this won't work:
var formValue = document.getElementById('#textForm').value;
Change that to
var formValue = document.getElementById('textForm').value;
if you want to use plain JavaScript - or do it the jQuery way, like so
var formValue = $('#textForm').value;
You could also have stored the reference to that DOM element in a var, up front, and then work on that, but that's another topic.
Also you must pass the formValue to the conversion function, like so
conversion(formValue);
otherwise you can't work with the input value within the function scope.
All that remains to do is writing the resulting value into the innerHTML of some . The other answers give you two options for doing that - in jQuery (innerHTML) or plain old JavaScript.

Better way to apply javascript scripts

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?
Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.
You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong
I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!

Categories

Resources