JavaScript function to hide buttons if specific text shows - javascript

I have a function called hideButtons that i want to hide buttons if certain text is present in the paragraph.
The paragraph goes through a list of names that the user either likes or dislikes and then when there are no more names then the buttons disappear.
Obviously this is sudo at the moment:
function hideButtons(){
if namespace.indexOf("Out of people"){
#likeButton = hidden;
#dislikeButton = hidden;
}
}
This is a working function
function showName(){
var name = names[0];
if (!name){
name = 'Out of people';
}
console.log(names)
document.getElementById('namespace').innerHTML = name;
}
And the html:
<body>
<p id='namespace'> Namelist </p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>

You are sort of mixing up javascript and jQuery.
In javascript, to get the value of a p tag:
var ns = document.getElementById('namespace').innerHTML;
the same thing in jQuery:
var ns = $('#namespace').text();
jQuery uses the CSS selectors to identify elements, javascript does not.
Here is a semi-working version of your code.
var lb = document.getElementById('likebutton');
lb.addEventListener('click', hideButtons, false);
var db = document.getElementById('dislikebutton');
db.addEventListener('click', hideButtons, false);
function hideButtons(){
var ns = document.getElementById('namespace').innerHTML;
alert(ns);
if (ns.indexOf("Namelist") > -1 ){
lb.style.display = 'none';
db.style.display = 'none';
}
}
function showName(){
var name = names[0];
if (!name){
name = 'Out of people';
}
console.log(names)
document.getElementById('namespace').innerHTML = name;
}
<body>
<p id='namespace'>Namelist</p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>
Here is the same code in jQuery:
$('#likebutton, #dislikebutton').click(function(){
var ns = $('#namespace').text();
if ( ns.indexOf('Namelist') > -1 ){
$('#likebutton').hide();
$('#dislikebutton').hide();
}else{
alert('P tag does not contain the word namespace');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<p id='namespace'>Namelist</p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>

Related

create the variable link as a hyperlink javascript

create a hyperlink with the variable link
<html>
<body>
<center><h1> retrive data</h1></center>
<h1 id="head1"> </h1>
<input type="text" placeholder="enter your unique id" id="pass"/>
<input type = "button" value = "submit" id="but" onclick="myfunction();"/>
<script>
var pass;
function myfunction()
{
pass = document.getElementById("pass").value;
document.writeln(pass);
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
var passwordToLookFor = pass;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once("value").then(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
var link = child.val().user_name;
document.writeln(link);
});
});
}
</script>
</body></html>
i want to create the value of link as a hyperlink
i want the hyperlink to be created once when the function is called
Are you just looking for how to make it an anchor tag?
<script>
var pass;
function myfunction()
{
...
var link = child.val().user_name;
document.writeln("<a href='"+link+"' target='_blank'>"+link+"</a>");
});
});
}
</script>
</body></html>
You can create an a dom element like this:
let link_el = document.createElement('a')
link_el.href = link // assuming link holds the value of the href you want
Then insert it into the dom wherever you want.
If I understand correctly and the link variable contains the actual address you want to navigate to, then this will work. First simply set an ID on the div you want to populate with links:
<div id="target-div"></div>
Then populate it like so (I just created an array for demo purposes, but this would be your snapshot.forEach:
var links = ['link1', 'link2', 'link3']
var targetDiv = document.getElementById("target-div");
links.forEach(function(link) {
var anchor = document.createElement('a');
anchor.href = link;
anchor.innerText = link;
targetDiv.appendChild(anchor);
var br = document.createElement('br');
targetDiv.appendChild(br);
});
Demo: https://jsfiddle.net/csnuh7rd/2/

put a save code in a text box and than change a variable to that save code

I'm back and i tried it but is doesn't work anyone that can help??? i have already put in the save mechanism.
(i had to add extra text so this has nothing to do with the script itself)
this is the code that i used to test the save mechanism.
<!DOCTYPE html>
<html>
<body>
<button onclick="point();">points</button>
<button onclick="upgrade()">upgrade</button>
<script language="javascript">
var pointcount = 0;
var totalcliks = 0;
var upgrades = 0;
function point() {
pointcount++;
totalcliks++;
}
function upgrade() {
upgrades++;
pointcount--;
}
function load() {
var testerload = document.getElementById("savecodetextbox").value;
document.getElementById("saveshow").innerHTML = testerload;
}
var pointcounterclock = setInterval(function() {pointcounter()},100);
function pointcounter(){
document.getElementById("points-screen").innerHTML = pointcount+" points";
document.getElementById("clicktotal").innerHTML = totalcliks+" totalcliks";
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
}
let savecode = "1a1a1"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[1];
updates = codes[2];
pointcount = codes[3];
}
</script>
<h3 id="points-screen"></h3>
<h3 id="clicktotal"></h3>
<h3 id="savecode"></h3>
<textarea name="text_area" id="savecodetextbox" rows="4" cols="40"></textarea> <button onclick="load()">load</button>
<h3 id="saveshow"></h3>
</body>
</html>
I'm going to alter your save code so I don't have to confuse you with regular expressions or funky splits:
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
Which means your save code could look something like: 4a6a9
Do a simple split:
let savecode = "4a5a6"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[0];
upgrades = codes[1];
pointcount = codes[2];
}
As for implementing the variables, reload the game after

onchange attribute: what exactly is the context when calling a function from this?

So I am trying to make a simple todo list, in which I have check boxes for each list item I create. Each time I change the checkbox associated with a certain task, I want to call a function that will have an if else statement. The if else statement will tell me if the box is checked or unchecked, and do code based on that logic. The problem is, I don't know how to access the specific checkbox I am referring to, since each task is created through javascript and does not have a unique id.
So with that being said my questions are:
How do I refer to the specific checkbox I am changing? do I use the "this" keyword? and if so, what exactly is "this" referring to in this particular circumstance?
Here is my js code:
$("#add").button();
$("#remove").button();
//Constructor for ToDo Object
function ToDo(name){
this.name = name;
}
ToDo.prototype.addItem = function(string){
var list = document.querySelector("#list");
var listItem = document.createElement("div");
var listItemPar = document.createElement("p");
var listItemText = document.createTextNode(string);
var checkBox = document.createElement("input")
checkBox.setAttribute('type','checkbox');
checkBox.className = "checkBoxes"
checkBox.setAttribute("onchange","checkedBoxes()")
var removeButton = document.createElement("button")
removeButton.className = "removeButtons"
list.appendChild(listItem);
listItem.appendChild(listItemPar);
listItemPar.appendChild(listItemText);
listItem.appendChild(checkBox);
listItem.appendChild(removeButton);
$("button.removeButtons").button();
$(".removeButtons").hide();
document.querySelector("#input").value = "";
};
ToDo.prototype.removeItem = function(){
console.log("remove item");
}
document.querySelector("#remove").addEventListener("click",function(){
item = new ToDo();
item.removeItem();
window.alert("hi");
})
document.querySelector("#add").addEventListener("click",function(){
var item = new ToDo();
item.addItem(document.querySelector("input").value);
})
function checkedBoxes(){
//function I am referring to
}
So in the code, I am referring to checkBox.setAttribute("onchange","checkedBoxes()"), and the function is at the bottom. The HTML is really not super important since I am creating almost everything through javascript, but if you need to look at it to help let me know.
Thanks in advance
To answer your question you have to pass the this keyword here checkBox.setAttribute("onchange", "checkedBoxes(this)")
The this refers to the current element.
Here is a working example
script.js
$(document).ready(function() {
//Constructor for ToDo Object
function ToDo(name) {
this.name = name || "";
}
ToDo.prototype.addItem = function(string) {
var list = document.querySelector("#list");
var listItem = document.createElement("li");
var listItemPar = document.createElement("p");
var listItemText = document.createTextNode(string);
var checkBox = document.createElement("input")
checkBox.setAttribute('type', 'checkbox');
checkBox.className = "checkBoxes"
checkBox.setAttribute("onchange", "checkedBoxes(this)")
var removeButton = document.createElement("button")
removeButton.setAttribute('type', 'button');
removeButton.className = "removeButtons"
list.appendChild(listItem);
listItem.appendChild(listItemPar);
listItemPar.appendChild(listItemText);
listItem.appendChild(checkBox);
listItem.appendChild(removeButton);
$(".removeButtons").hide();
document.querySelector("input").value = "";
};
ToDo.prototype.removeItem = function() {
console.log("remove item");
}
$("#remove").click(function(e) {
var item = new ToDo();
item.removeItem();
window.alert("hi");
});
$("#adder").click(function(e) {
console.log("add clicked");
var item = new ToDo("dd");
item.addItem(document.querySelector("input").value);
});
$("#list").css("border", "3px solid red");
});
function checkedBoxes(thisCheckbox) {
//function I am referring to
console.log(thisCheckbox);
}
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.0.1" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" data-semver="3.3.6" data-require="bootstrap-css#*" />
<script src="script.js"></script>
</head>
<body class="container">
<input type="text" name="userinput" />
<button type="button" id="adder">Add</button>
<button type="button" id="remove">Remove</button>
<hr />
<ul id="list" data-hello="world"></ul>
</body>
</html>

javascript copy div change innerHTML id

I need to copy content from one div to another one with changing button's id (increment them)
Sample:
<script type="text/javascript">
function add(){
document.getElementById('two').innerHTML = document.getElementById('one').innerHTML;
}
</script>
<div id="one">
<button id="button_1" >Button_1</button>
</div>
<div id="two"></div>
<button onclick="add();">Add</button>
This of course can't work properly.
Result should be following:
<div id="two">
<button id="button_2" >Button_2</button>
</div>
Any simple way how to do this ?
If you want copy the button onclick of a button it will work for you i guess..
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('one');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "one" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
<div id="one">
<button id="button_1" >Button_1</button>
</div>
<button id="button" style="color:red">Add</button>
I've made small change in 'id' of the wrapping div.
<div id="1" class="button">
<button id="button_1" >Button_1</button>
</div>
<button onclick="add();">Add</button>
<script type="text/javascript">
function add(){
var count = document.querySelectorAll('.button').length;
var newCount = count+1;
var elDiv = document.createElement('div');
elDiv.setAttribute("id", newCount);
elDiv.setAttribute("class", "button");
elDiv.innerHTML = '<button id="button_"+newCount+">Button_'+newCount+"</button>";
document.getElementById(count).appendChild(elDiv);
}
</script>
However it can be done in more simpler way using jQuery. Hope this helps.
Are you looking for something like this. With a good mastery of jQuery traversal you may not even need to give each button an id. May be a common class may serve you well.
$(function() {
var last = $('.container');
var curr = last;
$('#add').on('click', function() {
last = curr.clone();
last.find('button').attr('id', function() {
return 'button_' + ( $('div.container').length + 1 );
})
.html(function() {
return 'Button_' + ( $('div.container').length + 1 );
}).end()
.insertAfter( curr );
curr = last;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="button_1" >Button_1</button>
</div>
<button id="add">Add</button>
Using JQuery:
function add( fromId, toId ){
content = $('#'+fromId).clone();
button = content.find('button');
if( button.length == 1 ){
buttonId = button.attr('id');
number = buttonId.match(/\d+/g);
number = parseInt(number[0]) + 1;
button.attr('id','button_' + number);
button.html('Button_' + number);
}
$('#'+toId).html(content.html());
}
Just call
add('one','two');

Can't insert a div into another internal div

I need your help to solve a problem I have.
I have this code:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="aaa()"/>
</div>
</div>
I want to use insert into the internal div (id=edit1) another new div I generated.
I tried alike code but it's not running:
js:
function aaa()
{
var elem = createDivLine();
var el1 = document.getElementById("div1");
var el2 = el1.getElementById("edit1");
el2.appendChild(elem);
}
function createDivLine()
{
var tempDiv1 = document.createElement("div");
tempDiv1.innerHTML = "Sam";
return tempDiv1;
}
The result should looks like this:
<div id="div1" >
<div id="edit1">
hello
<input type="button" id="b1" onclick="createDivTable()"/>
<div>"Sam"</div>
</div>
</div>
JSFiddle: http://jsfiddle.net/KknXF/
Since IDs are unique, it is not valid to attempt to get an element's children by ID.
Remove this line:
var el1 = document.getElementById('div1');
And change the following line to:
var el2 = document.getElementById('edit1');
In the event that you have some irrepairably (I can never spell that word...) broken HTML that you can't possibly change, try this:
var el2 = document.querySelector("#div1 #edit1");
It should be
function aaa() {
var elem = createDivLine();
var el2 = document.getElementById("edit1");
el2.appendChild(elem);
}
Demo: Fiddle

Categories