I'm trying to create a to-do list. When I open up the html file (I'm using Google Chrome), there seem to be two issues:
The button doesn't appear to be a button, as in it doesn't click.
When I press enter instead of trying to click the add button, the text just disappears.
But in both cases, neither method appends the user input. What do I need to fix?
I have the following:
$(document).ready(function() {
$('#button').click(function() {
var toAdd = $('input[name=checkListItem]').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
});
h2 {
font-family: arial;
}
form {
display: inline-block;
}
#button {
display: inline-block;
height: 20px;
width: 70px;
background-color: #cc0000;
font-family: arial;
font-weight: bold;
color: #ffffff;
border-radius: 5px;
text-align: center;
margin-top: 2px;
}
.list {
font-family: garamond;
color: #cc0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" name="checkListItem" />
</form>
<div id="button">Add!</div>
<br/>
<div class="list"></div>
Giving something the id of button does not make it a button. Maybe you should try: <button id="button>Add!</button>
When you press enter you are submitting the form, since you don't have any javascript intercepting the onSubmit event for the form it reloads the page.
If you want this action to happen when the user hits Enter, then you should move the button inside of the form and change the event to $('form[name="checkListForm"]').on('submit', ...)
Ok so I see a few problems here. First of all a div is not a button. I mean you could maybe do styling to make it look like a button, but why not just use:
<button type="button"> Add </button>
Also, you could just use onclick instead of defining that click event. I find this usually cleaner:
<button type="button" onclick="the_function();"> Add </button>
And then in your javascript define the function:
function the_function()
{
var toAdd = $('input[name=checkListItem]').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
However, you are better off putting an id on the input like this:
<input type="text" id="check-list-input" name="checkListItem"/>
Obviously you don't need to use that naming convention. After doing that then you can revise that function to:
function the_function()
{
var toAdd = $('#check-list-input').val();
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
But yet this still isn't as good as it should be. The list should also be an id not a class. If you had more than one list on the page, it would cause problems. Instead do this:
<div class="list" id="list-div"></div>
And then you can revise your function to:
function the_function()
{
var toAdd = $('#check-list-input').val();
$('#list-div').append("<div class='item'>" + toAdd + "</div>");
});
So the end result should be:
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<h2>To Do</h2>
<form name="checkListForm">
<input type="text" id="check-list-input" name="checkListItem"/>
</form>
<button type="button" onclick="the_function();"> Add </button>
<br/>
<div class="list" id="list-div"></div>
</body>
</html>
and for your jQuery (no need for document ready anymore, just be sure to include the javascript file or snippet before the html):
function the_function()
{
var toAdd = $('#check-list-input').val();
$('#list-div').append("<div class='item'>" + toAdd + "</div>");
});
I didn't test this yet, but I hope it works for you.
Related
in the below example,by clicking the log button,it shows in the log the div's markup which consists of inputs without a predefined value attribute like this: <input><input><input><input><input><input>,even if i type some text in the inputs it logs the same thing.
i want to use the button #add to give all inputs the value attribute,and the content should be the current value of them,so next time i'll click log should show this : <input value"CURRENT VALUE.."><input value"CURRENT VALUE.."><input value"CURRENT VALUE.."><input value"CURRENT VALUE.."><input value"CURRENT VALUE.."><input value"CURRENT VALUE..">
is there a simple method to do this with jquery ?
$(document).on('click', '#log', function() {
console.log($('div').html())
});
$(document).on('click', '#add', function() {
//GIVE ALL INPUTS THE "value" ATTRIBUTE AND SET THEIR CURRENT VALUE AS CONTENT
});
input,
button {
float: left;
clear: both;
margin: 2px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<button id="log">LOG HTML</button>
<button id="add">ADD VALUE ATTRIBUTE</button>
<div>
<input><input><input><input><input><input>
</div>
</body>
</html>
Code-wise this is easy to solve, as the answers show. Yet this has a smell of you trying to do something wrong out of misunderstanding the value attribute.
It only serves a single purpose: Setting the initial value of an input declaratively, that is, in the markup. It is not meant to be refreshed as soon as the input's value changes.
The DOM element property that synchronizes with the value attribute is element.defaultValue.
That being said, here's simple plain vanilla Javascript solution:
const inputs = document.querySelectorAll('input');
document
.getElementById('add')
.addEventListener('click', () => {
for (const input of inputs) {
input.defaultValue = input.value;
}
});
document
.getElementById('log')
.addEventListener('click', () => {
document
.getElementById('html-log-area')
.textContent = [...inputs].reduce((acc, {outerHTML: o}) => `${acc}${o}\n`, '');
});
input,
button {
float: left;
clear: both;
margin: 2px;
}
#html-log-area {
clear: both;
display: block;
border: 4px dashed lightgrey;
padding: 20px;
position: relative;
}
<button id="log">LOG HTML</button>
<button id="add">ADD VALUE ATTRIBUTE</button>
<div>
<input><input><input>
</div>
<br/>
<pre id="html-log-area"></pre>
Connexo's answer is great and you should note that in the modern browser environment jquery's usefulness is waning.
For a more "pure jquery" answer see below:
$(document).on('click', '#log', function() {
console.log($('div').html())
});
$(document).on('click', '#add', function() {
//Iterate the inputs
$(".dynamicAttribute input").each(function() {
//If we have a value
if ($(this).val().length > 0) {
//Add the value attribute
$(this).attr("value", $(this).val());
}
});
});
input,
button {
float: left;
clear: both;
margin: 2px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<button id="log">LOG HTML</button>
<button id="add">ADD VALUE ATTRIBUTE</button>
<div class="dynamicAttribute">
<input><input><input><input><input><input>
</div>
</body>
</html>
I am a beginner in programming and also I am new to this community, I hope you can help me with my question.
I want to know how to redirect from page 1 to page 2 and, after that, immediately call an event of this page 2.
This is the code from page 1:
<!DOCTYPE HTML>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
/*it doesn't work (i dont know why)*/
$(document).ready(function recargar2() {
$("#chiclayo_p").trigger("onclick");
});
/*it doesn't work (i dont know why)*/
$(document).ready(function recargar3() {
$("#trujillo_p").trigger("onclick");
});
</script>
</head>
<body>
Option 1
<br>
Option 2
<br>
Option 3
</body>
</html>
This is the code from page 2:
<!DOCTYPE html>
<html>
<head>
<title>Page2</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js">
</script>
<script>
$(function () {
$('.filter').click(function () {
$(this).addClass('active').siblings().removeClass('active')
let valor = $(this).attr('data-nombre');
if (valor == 'lima') {
$('.lima').show('1000');
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
} else {
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
}
});
});
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'open sans';
background: #fff;
}
.botones li {
display: inline-block;
text-align: center;
margin-left: 20px;
margin-bottom: 20px;
padding: 6px 12px;
border: 1px solid blue;
list-style: none;
color: blue;
}
.botones li:hover {
background: yellow;
color: red;
cursor: pointer;
}
.botones .active {
background: rgb(158, 218, 158);
}
.galeria {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
overflow: hidden;
}
</style>
</head>
<body>
<div class="botones">
<ul>
<li class="filter active" data-nombre='lima' id="lima_p">Lima</li>
<li class="filter" data-nombre='chiclayo' id="chiclayo_p">Chiclayo</li>
<li class="filter" data-nombre='trujillo' id="trujillo_p">Trujillo</li>
</ul>
</div>
<div>
<div class="galeria" id="options">
<div class="contenedor lima">
<h1> This is the option 1 - Lima!!!</h1>
</div>
<div class="contenedor chiclayo" style="display: none">
<h1> This is the option 2 - Chiclayo!!!</h1>
</div>
<div class="contenedor trujillo" style="display: none">
<h1> This is the option 3 - Trujillo!!!</h1>
</div>
</div>
</div>
</body>
</html>
What I can't find how to solve is that when I click on option 2 on page 1, in addition to opening page 2, it should show me the selected option "Chiclayo" and the self content of this option; I would like the same thing to happen when clicking on option 3 on page 1, which should select the option "Trujillo" and show me its content. I have tried with the "onclick" event but I have not obtained results, I do not know if it is the correct way or there are better options; maybe with javascript or jquery code. I appreciate you could help me with my query.
First, as you called it on Page 2, you need to implement jQuery on Page 1.
Page 1 also needs to be called. For the jquery script codes that you write to work.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js">
for redirect;
$( "#other" ).click(function() {
window.location = "/Page2.html#chiclayo_p";
});
You can pass the option Id as query parameter in click function of a button like this on page 1
<a onclick="recargar('lima_p');">Option 1</a>
<br>
<a onclick="recargar('chiclayo_p');">Option 2</a>
<br>
<a onclick="recargar('trujillo_p');">Option 3</a>
then redirect the page 1 to page 2 to pass this value like this
function recargar(option) {
window.location.href = "page2.html" + "#" + option;
}
On page 2 you can fetch this query parameter and highlight the selected option and display related content, like this
// Add function body -- <body onload="onload()">
function onload() {
var option = window.location.hash.substring(1);
var element = $("#" + option);
alert(element);
highlightDiv(element);
}
function highlightDiv(option) {
$(option).addClass('active').siblings().removeClass('active')
let valor = $(option).attr('data-nombre');
if (valor == option) {
$('.lima').show('1000');
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
} else {
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
}
}
$(function () {
$('.filter').click(function () {
highlightDiv(this);
});
});
What you can do is pass the selected option as a query parameter and then redirect from page 1 to page 2. Then, on ready event of page 2, you can read the query parameter being passed and display your div accordingly.
Basing on this question, you can do that by using either cookies or local storage, query parameter.
As Fizer Kahn said in his answer, the most recommended way is query parameter.
On my web app, I have a screen that expects a user to use a bar-code scanner to scan an item number in, but in the event they do not have one (or the code won't scan) they can click on the notification that asks them to scan and it changes to a box allowing them to enter the details to search manually.
The issue is, the event listener seems to get applied to the close button, it gets removed from the div but the close button seems to call the "open search box" function instead of the "close search box" function
I tried using the jQuery $('#id').one('click' function(){myFunctionHere();}); function to add an event listener on click of the DIV and also tried using $('#id').on('click' function(){myFunctionHere();}); and $('#id').off('click'); but I have the same issue.
See the jsfiddle
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<style>
#tnt-searchScan{
width: 300px;
height: 100px;
border: 5px dashed red;
text-align: center;
}
</style>
<script>
$(document).ready(function(){
$('#tnt-searchScan').one('click', function(){showSearchBox();});
})
function closeSearchBox(){
var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
$('#tnt-searchScan').html(html).one('click', function(){showSearchBox();});
}
function showSearchBox(){
console.log('test');
var html = 'Content of search box<button type="button" id="tnt-closeSearchBox">Close</button>';
$('#tnt-searchScan').html(html);
$('#tnt-closeSearchBox').one('click', function(){closeSearchBox();});
}
</script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>
I expect the box to return back to normal, but it does not, if you check the console, every time you click 'Close' "test" appears, signalling that the show function is called. if i call the "closeSearchBox();" manually it works fine.
You need to make some changes in your js. First of all .one is changed to .on second need to change the close function click event because the search form is added with js to dom so you need to fire click event on it like this $(document).on('click','#tnt-closeSearchBox', function(){ closeSearchBox(); });.
$(document).ready(function(){
$('#tnt-searchScan').on('click', function(){showSearchBox();});
})
function closeSearchBox(){
var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
$('#tnt-searchScan').html(html).on('click', function(){showSearchBox();});
}
function showSearchBox(){
//console.log('test');
var html = '<label>Search By: <select id="tnt-searchOption">' +
'<option selected>ID</option>' +
'<option>Legacy ID</option>' +
'</select></label>' +
'<label>Search: <input type="text" id="tnt-searchBox"></label>' +
'<button type="button">Search</button><button type="button" id="tnt-closeSearchBox">Close</button>';
$('#tnt-searchScan').html(html);
}
$(document).on('click','#tnt-closeSearchBox', function(){closeSearchBox();});
#tnt-searchScan{
width: 300px;
height: 100px;
border: 5px dashed red;
text-align: center;
}
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>
Goal is to use a keypress event handler to take form input and use that input to replace the current page with another using redirect to a new fully qualified URL based partially on the input value. Input is submitted by pressing the Enter key. Keypress event is "handled" correctly but redirect doesn't do anything. I realize I can make this work using
<form onsubmit=myfunction()"
but would prefer to use an event handler approach for a variety of reasons.
Here is sample HTML/Javascript that demonstrates the problem:
var i_Parent = document.getElementById('inputs');
i_Parent.addEventListener('keypress', handleKeypress, false);
function handleKeypress(e) {
var id = e.target.id;
var value = e.target.value;
var name = e.target.className;
var node = e.target.nodeName;
if (node == 'INPUT' && e.keyCode == 13) {
console.log('Node=' + node + ' Id=' + id + ' Name=' + name + ' Value=' + value);
try {
console.log('In try{}');
location.replace('https://google.com');
window.location = 'https://google.com';
console.log('No exception in try{}');
return false;
} catch (e) {
console.log('In catch()');
return false;
}
}
e.stopPropagation();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Appropriate Title Description</title>
<style type="text/css">
body {
background-color: #d9d9d9;
width: 90vw;
margin: 0 auto;
}
input[type=number] {
font-size: 2.8vmin;
font-family: Arial, verdana;
width: 3.2em;
padding: 1px 0px;
border: 1px solid gray;
background-color: #5600bb;
color: white;
}
</style>
</head>
<body>
<h2>Testing Form Input</h2>
<div id='inputs'>
<form> Spread =
<input id='spread' type='number' min='.10' max='2.0' step='.05' , size='4' maxlength='4' value='1.0'> %
</form>
</div>
</body>
</html>
an interesting pickle! I think the problem is because you're using the enter key, which by default is submitting the form which reloads the page. If you used a different key it wouldn't be a problem.
I think adding this fixes it (I put it just before the if statement):
e.preventDefault();
preventDefault doco here at Mozilla
If you add other html controls this might impact them though (I think it would stop space letting you select a checkbox?). So maybe you would only want to do it directly before calling the location.replace
I just have a question about how I would make it so that there is a button in one column and when you click the button, text appears in another column. My overall goal is to make a simple clicker.
Here is my code:
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Clicker</title>
<meta name="generator" content="BBEdit 11.6" />
</head>
<body>
<table width=600>
<tr>
<td width=300><span><font size=24px><button onclick='onClick()'>
click me
</button></span></td>
<td sidth=300><span><font size=24px>So does this</span></td>
</tr>
</table>
<script>
clicks = 0;
function onClick () {
clicks = (clicks + 1);
document.write ("you have clicked the button ")
document.write (clicks)
document.write (" times")
};
</script>
</body>
</html>
I have what I need to make it so that you get a message when you click the button, but when I do, all the other text dissipears and I get just that message. Tell me if it was a really stupid mistake or not please. I need to know.
To show the count of clicks in the page, and keep your html, a simple way to achieve that is adding a div and manipulate only its content with getElementById (to get the element) and then call innerHTML (to change the content of an HTML element).
Add this bellow your html table:
<div>
<h1 id=click-event> </h1>
</div>
And change your onClick():
function onClick () {
clicks = (clicks + 1);
document.getElementById("click-event").innerHTML = "you have clicked the button " + clicks + " times";
};
Create an annonymous function when you click the button and call the counting() function. This will increase the value of the variable countingClicks and then set the innerText of the element in the other column to that variable.
var x = document.getElementById("counter");
var y = document.getElementById("display");
var countingClicks = 0;
function counting() {
countingClicks++;
y.innerText ="Number of times clicked: " + countingClicks;
}
//When the counter button is clicked call counting
x.onclick = function(){
counting()
}
.container{
width: 600px;
box-sizing: border-box;
}
.row{
display: flex;
flex-wrap: wrap;
width: 100%;
}
.six{
width: 48.33%;
text-align: center;
border: 1px solid black;
}
<div class="container">
<div class="row">
<div class="six">
<button id="counter">Counter</button>
</div>
<div class="six">
<span id="display"></span>
</div>
</div>
</div>
With peace and love for a confusing question.
<button onclick="a='textContent';t[a]=t[a].replace(/\d+/,++this[a])">0</button><p id=t>Total:0