I have a 'like' button; and underneath the button, I can display the 'like count'.
However, I want the 'like count' value to be displayed on the actual button itself. For example, I want the button to say: "Like 5"
How can I display both text and a variable value on a button?
Maybe you can improving with this code that i did.
HTML
<form id = "form" method = "POST">
<input type = "submit" value = "Like" />
</form>
<br />
<div id = "clicks">
counter = <label id = "count">0</label> clicks !
</div>
JS
function CountOnFormSubmitEvent(form_id, _callback_)
{
var that = this, count = 0, callback = _callback_;
var form = document.getElementById(form_id);
if(form === null) { return null; }
var reset = function(){
count = 0;
};
form.addEventListener("submit", function(evt){
callback(evt, ++count, reset);
}, false);
}
//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
event.preventDefault();
if(count >= 10)
{
alert("Reseting the process");
reset_callback();
}
document.getElementById("count").innerHTML = count;
});
Here is the link Jsfiddle.
DEMO JSFIDDLE
Related
So I am trying to make an edit function for a favorites bar. Editing one box is okay, but when I try to edit a different box, all the boxes that I clicked on previously gets edited as well. Here is a jsfiddle with the complete code: https://jsfiddle.net/1exrf9h8/1/
I am trying to understand why my editFavorite function is updating multiple boxes and not just one.
function clickEdit(input, title, url, plus, editIcon, anchorEdit, editBtn)
{
let i = editIcon.length - 1;
editIcon[i].addEventListener("click", function(event){
input.style.display = "block";
title.value = plus[i + 1].textContent;
url.value = anchorEdit[i].href;
console.log(i);
console.log(anchorEdit[i]);
editFavorite(anchorEdit[i], url, title, input, editBtn);
});
}
function editFavorite(changed, url, title, input, editBtn)
{
editBtn.addEventListener("click", function(){
changed.href = url.value;
changed.textContent = title.value;
input.style.display = "none";
});
}
There is a few problems in your logic, architecture and use of the event handler, Let's give it a shot in a more OOP way so you can actually make it to work and understand what is going on.
Every single favorite is an object by itself, that can spawn and update itself.
function favorite(newTitle, newUrl) {
this.element = container.appendChild(document.createElement("div"));
this.title = this.element.appendChild(document.createElement("h2"));
this.url = this.element.appendChild(document.createElement("h2"));
this.update = (newTitle, newUrl) => {
this.title.textContent = newTitle;
this.url.textContent = newUrl;
}
this.createButton = () => {
button = this.element.appendChild(document.createElement("button"));
button.append("Edit");
button.addEventListener("click", () => {
let titleInput = document.getElementById("title").value;
let urlInput = document.getElementById("url").value;
this.update(titleInput, urlInput);
})
}
this.update(newTitle, newUrl);
this.createButton();
}
Then let's have a simple form where we can take inputs, using the same for editing, and creating a new favorites.
<input id="title" type="text" name="title" placeholder="Title">
<input id="url" type="text" name="url" placeholder="Url">
<button id="submit">Create New</button>
Now the actual submit logic.
document.getElementById("submit").addEventListener("click", () => {
let titleInput = document.getElementById("title").value;
let urlInput = document.getElementById("url").value;
if (!titleInput.length || !urlInput.length) return;
let newFavorite = new favorite(titleInput, urlInput);
container.appendChild(newFavorite.element);
});
https://jsfiddle.net/p50L27us/48/
The problem is caused by editFavorite function. when you call editFavorite function automatically starts new listener. Evey click start new one.
The solution is " ,{once : true} "
function editFavorite(changed, url, title, input, editBtn)
{
editBtn.addEventListener("click", function(){
changed.href = url.value;
changed.textContent = title.value;
input.style.display = "none";
},{once : true});
}
In a js code, i created 3 buttons --- button 1...button 2...button 3
and 3 input fields --- input field 1...input field 2...input field 3
From the beginning of the script all buttons are disabled
button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values
button 2 will only be activated when input field 1 and 3 have numerated values
button 3 will only be activated when input field 2 and 3 have numerated values.
My problem is when i entered a numerated value for input field 1 and 2, button 1 will not activate (in-clickable) even though it was suppose to
And lets say i redid my code and got my whole code backwards so, at the beginning of my script all the buttons were not disabled (you could click on them). Then i made a simple conditional statement like so
input field 1 = if1
input field 2 - if2
if (if1.length = 0 || isNaN(if1) && if2.length = 0 || isNaN(if2) ) {
document.getElementById("button 1").disable = true;
}
Button 1 will not immediately disable until the user clicks on the button. And if the user were to re-enter the appropriate value type in input field 1, button 1 will not activate (be-clickable) because apparently its permanently disabled.
So down to summary, I'm asking if there is a way to make JavaScript be instantly interactive. Such as a web browser search bar. The moment you type something, you immediately get a list of possible questions and when you don't type anything in them the list disappears and the browser regains its original state.
Any Advice/help shall be greatly appreciated
Due to Life and its problems my code some how got deleted. Thus the lack of code and bunch of words. Sorry.
Generic solution (using attributes)
You can check the answer below which is using oninput event and the attributes to handle your situation effectively.
I have added a data-target attribute to link the elements together to fit with your requirement.
For an instance, to match the rule button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values, data-target of button1 is id of textbox 1 & 2.
Working snippet:
function checkInput() {
var dataTarget = 'data-target';
var elm = event.target;
var targetAttrs = getAttr(elm, dataTarget);
if(targetAttrs) {
var targetButtons = targetAttrs.split(',');
for(var i = 0; i < targetButtons.length; i++) {
var button = document.getElementById(targetButtons[i]);
targetAttrs = getAttr(button, dataTarget);
if(targetAttrs) {
var targetTextBoxes = targetAttrs.split(',');
var valid = true;
for(var j = 0; j < targetTextBoxes.length; j++) {
var textBox = document.getElementById(targetTextBoxes[j]);
if(textBox) {
valid = isValidNumber(textBox.value);
}
if(!valid) {
break;
}
}
button.disabled = !valid;
}
}
}
}
function isValidNumber(val) {
return (val && val.length > 0 && !isNaN(val));
}
function getAttr(elm, name){
var val;
if(elm) {
var attrs = elm.attributes;
for(var i = 0; i < attrs.length; i++) {
if(attrs[i].name === name) {
val = attrs[i].value;
break;
}
}
}
return val;
}
<div>
<input type="text" id="textBox1" oninput="checkInput()" data-target="button1,button2" />
</div>
<br/>
<div>
<input type="text" id="textBox2" oninput="checkInput()" data-target="button1,button3" />
</div>
<br/>
<div>
<input type="text" id="textBox3" oninput="checkInput()" data-target="button2,button3" />
</div>
<br/>
<input type="button" id="button1" value="Submit" data-target="textBox1,textBox2" disabled />
<input type="button" id="button2" value="Submit" data-target="textBox1,textBox3" disabled />
<input type="button" id="button3" value="Submit" data-target="textBox2,textBox3" disabled />
Note: With this code, when you add more elements, you don't need to change/add any Javascript code. Just add the elements and attributes
var field1 = document.getElementById('if1');
var field2 = document.getElementById('if2');
var field3 = document.getElementById('if3');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
field1.addEventListener('input', function(){
if(this.value!= '' && field2.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button2.disabled = false;
else
button2.disabled = true;
});
field2.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
field3.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button2.disabled = false;
else
button2.disabled = true;
if(this.value!= '' && field2.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
<input type="text" id="if1">
<input type="text" id="if2">
<input type="text" id="if3">
<br>
<button type="button" id="button1" disabled="true">Button1</button>
<button type="button" id="button2" disabled="true">Button2</button>
<button type="button" id="button3" disabled="true">Button3</button>
Here is how you do it
Disabling a html button
document.getElementById("Button").disabled = true;
Enabling a html button
document.getElementById("Button").disabled = false;
Demo Here
Edited
Try this...
You apply addEventListener to that DOM object:
document.getElementById("IDTeam").addEventListener("change", function() {//call function here});
For IE
document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} );
I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>
I am trying to create a form which will take the user input to create a query for database. I have three buttons: And, Or, Run.
I am creating dynamic elements on click of buttons And and Or.
The div search_list is the container for containing the elements.
I need the form to be submitted on click of Run.
The weird thing is, whenever I click on any button the form gets submitted. How do I stop it ? Please let me know If you need more info.
Thanks
<html>
<head>
<script type="text/javascript">
var count = 0;
function loadfirst(){
count=1;
addFilter('');
}
function addFilter(flag){
var div = document.querySelector("#search_list");
tr = document.createElement("tr");
select = document.createElement("select");
var sear_value = document.createElement("input");
var and_or = document.createTextNode(flag);
tr.id='tr_'+count;
select.id='sl_'+count;
sear_value.id='sear_value_'+count;
select.options.add( new Option("user id","user_id", true,true) );
select.options.add( new Option("First name","first_name"));
select.options.add( new Option("Last name","last_name"));
select.options.add( new Option("Course","course"));
sear_value.type="text";
if(count<=1){
var bt_and= document.createElement("button");
bt_and.id='and';
var bt_label = document.createTextNode("And");
bt_and.appendChild(bt_label);
bt_and.addEventListener('click', function() {
addFilter('and');
return false;
});
var bt_or= document.createElement("button");
bt_or.id='or';
var bt_label = document.createTextNode("Or");
bt_or.appendChild(bt_label);
bt_or.addEventListener('click', function() {
addFilter('or');
return false;
});
}
else{
var bt_rem= document.createElement("button");
bt_rem.id='rem_'+count;
var bt_label1 = document.createTextNode("x");
bt_rem.appendChild(bt_label1);
var tr_id = 'tr_'+count;
bt_rem.addEventListener('click', function() {
var element= document.getElementById(tr_id);
element.parentNode.removeChild(element);
return false;
});
}
tr.appendChild(and_or);
tr.appendChild(select);
tr.appendChild(sear_value);
if(count<=1){
tr.appendChild(bt_and);
tr.appendChild(bt_or);
}
else{
tr.appendChild(bt_rem);
}
div.appendChild(tr);
count++;
}
function getFilter(){
alert();
}
</script>
</head>
<body onload="loadfirst()">
<span id='manage_stud_header' class= 'list_header'>
<label><?php echo $module_name;?></label>
<center>
<form>
<div id='search_list' class='search'></div>
<button id="run_filter" type="submit">Run</button>
</form>
</center>
</span>
</body>
</html>
The default type for buttons is "submit", so you have to explicitly say you want a plain button:
var bt_and= document.createElement("button");
bt_and.type = "button";
This way it won't submit the form when clicked. (unless of course you tell it to :))
you have to change
<button id = "run_filter" type = "submit" > Run </button>
in
<input id = "run_filter" type = "submit" value="Run" />
and then if the behaviour of click on button is forced to reload the page try to change button on other form element or see e.preventdefaulT of jquery
Here's a demo of what I'm talking about - http://jsfiddle.net/MatthewKosloski/qLpT9/
I want to execute code if "Foo" has been clicked, and a number has been entered in the input.. and if "send" has been clicked.
<h1>Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="send">Send</button>
I'm pretty sure I'm overthinking this, I'd appreciate the help on such a concise question.
try this one: jfiddle link
var send = document.getElementById("send");
var h1 = document.getElementsByTagName("h1");
var foo_clicked = 0;
h1[0].onclick = function(){foo_clicked += 1; };
send.onclick = function(){
if(document.getElementById("amount").value !='' && foo_clicked >0 )
alert ('poor rating');
};
As per your statement & taking some assumptions, try this way:
(This executes function twice - When there is a change of text or a click of the button).
HTML:
<h1 id="">Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="sendBtn">send</button>
JS:
document.getElementById("amount").addEventListener("change",poorRatingCalculation);
document.getElementById("sendBtn").addEventListener("click",poorRatingCalculation);
function poorRatingCalculation() {
var rating = document.getElementById("amount").value;
if(rating=="poor") alert("Poor Service");
}
DEMO: http://jsfiddle.net/wTqEv/
A better, self contained example:
http://jsfiddle.net/qLpT9/7/
(function()
{
var clicked = false;
var header = document.getElementById("header");
var amount = document.getElementById("amount");
var send = document.getElementById("send");
header.addEventListener("click", function()
{
clicked = true;
});
send.addEventListener("click", function()
{
if(!clicked)
{
return
}
// Foo has been clicked
var value = amount.value;
console.log(value;)
});
})();
Is this what you were looking for?
http://jsfiddle.net/qLpT9/5/
function poorRatingCalculation(){
if(myInput.value) {
alert(myInput.value);
}
}
var foo = document.getElementById("foo"),
myInput = document.getElementById("amount");
foo.addEventListener("click", poorRatingCalculation, false)