I'm just messing around on JavaScript. I want to create two single on-click buttons, each which serve separate functions. However, the first button's response is always that of the second if that group of code is in. It works fine independently.
I've double checked online and tried a few functions, but everything comes back to multiple-function buttons.
I'm not super advanced and I just do random programming for fun.
If the yes button is clicked, then "Good" should appear. If the no button is clicked, then "Bad" should appear.
When both groups of code are together, "Bad" is always shown, regardless of the button shown. If only the first group of code is isolated, then the result is "Good".
function myFunction() {
var str = "Good";
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById("happy").innerHTML = result;
}
</script>
<button onclick="myFunction()">No</button>
<p id="sad"></p>
<script>
function myFunction() {
var str = "Bad";
var result = str.link("https://www.tacobell.com/");
document.getElementById("sad").innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myFunction()">Yes</button>
<p id="happy"></p>
You can also use a single click event function for both of your buttons.
See below code -
function myFunction(elem) {
var btnHtml = elem.innerHTML;
var str = "Good";
var id = "happy"
if(btnHtml == "No"){
str = "Bad";
id = "sad";
}
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById(id).innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myFunction(this)">Yes</button>
<p id="happy"></p>
<button onclick="myFunction(this)">No</button>
<p id="sad"></p>
You can do something like this, one function for both onclick events.
HTML
<p>Click the button to trigger a function.</p>
<button onclick="myFunction('yes')">Yes</button>
<button onclick="myFunction('no')">No</button>
<p id="demo"></p>
Javascript
function myFunction(value)
{
document.getElementById("demo").innerHTML=value;
}
Here's the fiddle
http://jsfiddle.net/840Larsn/
It is because you are using Function constructor and the functions are created in the global scope and therefore the second function overwrites the first one.
You can refer to here to see the definition.
You can use jquery if you wish,its simple
$('.clickbtn').click(function(e){
var str,result ;
var data = $(this)
if(data.attr('data-id')==1)
{
str = "Good";
result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
$("#text").html(result)
}
else
{
str = "Bad";
result = str.link("https://www.tacobell.com/");
$("#text").html(result)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Do you like tacos?
<br />
<button class="clickbtn" data-id=1>Yes</button>
<button class="clickbtn" data-id=2>No</button>
<p id="text"></p>
You should name your function differently:
In fact when you declare the second function in your original code it overwrites the first one because they have the same name.
function myGoodFunction() {
var str = "Good";
var result = str.link("https://www.allrecipes.com/search/results/?wt=authentic%20taco%20recipes&sort=re");
document.getElementById("happy").innerHTML = result;
}
function myBadFunction() {
var str = "Bad";
var result = str.link("https://www.tacobell.com/");
document.getElementById("sad").innerHTML = result;
}
Do you like tacos?
<br />
<button onclick="myGoodFunction()">Yes</button>
<p id="happy"></p>
<button onclick="myBadFunction()">No</button>
<p id="sad"></p>
Related
I build a little snippet with javascript to add more fields by clicking a button. It works fine and add the field as it should but it discards the values of the already existing fields on clicking the add more button.
You can run the snippet below to check the issue ... Please add 2-3 fields and type something in those fields and then add another field. You'll see what is happening.
var fldsContainer = document.getElementById('fields');
var fld = '<p><input name="test[]" type="text"></p>';
function addField() {
fldsContainer.innerHTML += fld;
}
<div id="fields"></div>
<button onclick="addField()">Add More Field</button>
I know in jQuery we can simply .append() but I need a solution in javascript. Is there append method in javascript?
Or any other method to resolve my issue would be appreciated :)
It is because the content of fldsContainer is rerendered every time with a brand new list of fields. You need to append to the container. Try something like the insertAdjacentHTML() method.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
var fldsContainer = document.getElementById('fields');
var fld = '<p><input name="test[]" type="text"></p>';
function addField() {
fldsContainer.insertAdjacentHTML('beforeend', fld);
}
<div id="fields"></div>
<button onclick="addField()">Add More Field</button>
It may seem larger and maybe overkill but i prefer tracking all my inputs into an array so that i separate myself from needing to possibly query DOM elements in future.
var fldsContainer = document.getElementById('fields');
var fields = [];
function render() {
fldsContainer.innerHTML = getFields();
}
function addField() {
fields.push(fields.length ? getField(fields.length) : getField(0));
render();
}
function setValue(input, i) {
fields[i].value = input.value;
}
function getFields() {
var str = ''
fields.forEach(function(field) {
str += (`<p><input name="${field.name}" value="${field.value}" type="text" onchange="setValue(this, ${field.index})"></p>`);
});
return str;
}
function getField(index) {
return {
index,
name: `test${index}`,
value: ''
}
}
<div id="fields"></div>
<button onclick="addField()">Add More Field</button>
I am doing a visualization using D3 on zeppelin and I need to link Scala variable with javascript one.
In a simple way, I have the following three paragraphs:
1)
z.angularUnbind("aux")
z.angularBind("aux", "original value")
2)
%angular
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
if (document.getElementById("demo").innerHTML === ""){
document.getElementById("demo").innerHTML = "Hello World";
aux = "If"
}else{
document.getElementById("demo").innerHTML = "";
aux = "Else"
}
}
</script>
3)
z.angular("aux")
And I hope the following results:
Before click on "Click me" button I hope: aux = "original value".
After one click on "Click me" button I hope: aux = "If"
After two click on "Click me" button I hope: aux = "Else"
How to link javascript "aux" variable with angular's "aux"?
I finally found how to do that:
Paragraph 1) and 3) are equal to those showed in question. Into pragraph 2) aux variable is modified by write in a angularjs input field and reacting on change with z.angularBind(..) method. It allows to bind aux variable with another value. z.angularBind(..) method's third argument is the identifier of paragraph 3).
2)
%angular
<button onclick="myFunction()">Click me</button>
<input id="tb" class="hide" ng-model="aux" ng-change="z.angularBind('aux',aux,'20161224-171923_464920272')"></input>
<p id="demo"></p>
<script>
function myFunction() {
var element = $('#tb');
if (document.getElementById("demo").innerHTML === ""){
document.getElementById("demo").innerHTML = "Hello World";
element.val("If");
}else{
document.getElementById("demo").innerHTML = "";
element.val("Else");
}
window.setTimeout(function() {
return element.trigger('input');
}, 500);
}
</script>
I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.
This is a the portion I am working on, trying to get button '7' to register so I can do the others.
<div class="container-fluid calc" >
<div class="display">
<label type="text" id="screen">0</label>
<div class="buttons">
<button onClick='calculate()' id='myButton'>7</button>
<button>8</button>
<button>9</button>
Here is the JS I put together
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();
You need to update from
var num = document.getElementById('#myButton').contentValue;
to
var num = document.getElementById('myButton').innerHTML;
You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
Hope this helps!
Update
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
to
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}
Another option is you can is data attribute like this :
<button onClick='calculate()' id='myButton' data-value="7">7</button>
and get it like this :
$("#myButton").attr("data-value");
I managed to save the text that is in the input field but the problem is that i do not know how to save the button. The buttons turn white when i click on them and the price of that seat will be visible in the input field. The price saves but the button does not stay white.
<script>
function changeBlue(element) {
var backgroundColor = element.style.background;
if (backgroundColor == "white") {
element.style.background = "blue";
add(-7.5)
} else {
element.style.background = "white";
add(7.5)
}
}
function add(val) {
var counter = document.getElementById('testInput').value;
var b = parseFloat(counter,10) + val;
if (b < 0) {
b = 0;
}
document.getElementById('testInput').value = b;
return b;
}
function save(){
var fieldValue = document.getElementById("testInput").value;
localStorage.setItem("text", fieldValue)
var buttonStorage = document.getElementsByClass("blauw").value;
localStorage.setItem("button", buttonStorage)
}
function load(){
var storedValue = localStorage.getItem("text");
if(storedValue){
document.getElementById("testInput").value = storedValue;
}
var storedButton = localStorage.getItem("button");
if(storedButton){
document.getElementsByClass("blauw").value = storedButton;
}
}
</script>
<body onload="load()">
<input type="text" id="testInput"/>
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blauw" type="button" id="testButton2" value="click me to turn white"
style="background-color:blue" onclick="changeBlue(this)">
<input class="blauw" type="button" id="testButton2" value="click me to turn white"style="background-color:blue" onclick="changeBlue(this)">
</body>
i made a small sample of what i want to do. And i do not want to use the Id's of the buttons because i have like 500 of them in a table.
That's because getElementsByClass (it's getElementsByClassName btw) returns a node list of all the elements with that class.
To make it work, you need to go through all the items in the list, using a for-loop, and set the value of each individual element to the localStorage-value.
See these links for more information:
Link 1
Link 2
Very small mockup to give you an idea:
(In the JS, I put in comments the lines of code you would be using for your situation.)
function changeValues() {
var list = document.getElementsByClassName("child"); //var list = document.getElementsByClassName("blauw");
for (var i=0; i<list.length; i++) {
list[i].innerHTML = "Milk"; //list[i].value = storedButton;
}
}
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<p>Click the button to change the text of the first list item (index 0).</p>
<button onclick="changeValues()">Try it</button>
I have the following HTML,two buttons and a paragraph code, and javascript, like the following:
// HTML
<input type="button" onclick="insert()" value="insert"/>
<input type="button" onclick="delete()" value="delete"/>
<p id='text'>
Line 1
Line 2
</p>
//javascript
function insert(){
// ?
}
function delete(){
// ?
}
When the user clicks the delete button, the Line 1 and Line 2 will be deleted.
When the user clicks the insert button, the Line 1 and Line 2 will be inserted.
The Line 1 and Line 2 will be only insert when they are not between the <p id='text'>.
Can anyone help me?
For insert(), how about
document.getElementById('text').innerHTML = 'Line 1\nLine 2';
and for delete(), how about
document.getElementById('text').innerHTML = '';
Please note that delete is a JavaScript keyword (and it's even actually implemented, which is more than I can say for the utterly excessive amount of reserved keywords that JavaScript has). You will need to name your delete() function something else.
With jQuery you can try:
$("#text").text('');
You could something quick and easy with jQuery... adding ids to your buttons.
$('#delete').click(function(){
$('#text').html('');
})
$('#insert').click(function(){
$('#text').html('Line 1 Line 2');
})
http://jsfiddle.net/jasongennaro/MTJxH/1/
function insert() {
var para = document.getElementById("text");
if(para.innerHTML === "") {
para.innerHTML = "line1<br />line2";
}
}
function remove() {
document.getElementById("text").innerHTML = "";
}
However, please notice that I've changed the name of your delete function, because delete is a JavaScript keyword, and can't be used as the name of a function.
Here's a working example.
function insert() {
var p = document.getElementById('text');
if (p.innerHTML == '') {
p.innerHTML = 'Line 1<br />Line 2';
}
}
function delete() {
document.getElementById('text').innerHTML = '';
}
function delete(){
$('#text').html('');
}
function insert(){
if($('#text').text()=="")// add only if nothing inside
{
$('#text').html('Line 1 Line 2');
}
}
function delete()
{
var delMe = document.getElementById('text');
delMe.innerHTML = '';
}
function insert()
{
var insMe = document.getElementById('text');
insMe.innerHTML = "Line 1\r\nLine2";
}
Easy peasy.