How make input RESET Button?
INFO:
Hi I'm trying to do that if I click on my input which has the ID search-input so that if I write something in the input then class cancel which is the cross that resets the value it's like <button type =" reset "> so if I write something so that it appears to me sodisplay: block;and if I delete or input it won't have a value to dodisplay: none;and I would like to do all this to make it work even if the user doesn't have Javascript so I would like to do it in PHP version but I don't know what I have so far I only have this code which shows the icon when something is in the input but unfortunately the code has stopped working and especially when I delete the input via the button so the icon doesn't disappear for more information be sure not to be afraid to ask.
const input = document.getElementById("search-input")
const button = document.getElementById("cancel")
const icon = document.getElementById("icon")
input.addEventListener('keyup', test);
button.addEventListener("button", test)
function test() {
let isShown = false
if (input.value.trim() == "" || isShown == false) {
icon.style.display = "none"
isShown = true
} else {
icon.style.display = "flex"
}
}
PS: Everything was translated by Google translator if there was a mistake or you did not understand something write and I will definitely tell you how it should be thought in advance thank you very much for your help.
I think Uttam Nath's answer was close to what you wanted but not exactly. This may work better:
EDIT: Alright I changed the code a bit and I added the HTML with it so there is no confusion.
<body>
<input type="text" id="search-input">
<button type="button" id="cancel">Cancel</button>
<div id="icon" style="background-color: green; width: 50px; height: 50px; display: none;"></div>
</body>
<script>
const input = document.getElementById("search-input");
const button = document.getElementById("cancel")
const icon = document.getElementById("icon");
input.addEventListener('keyup', changeIconDisplay);
button.addEventListener('click', () => {
input.value = '';
changeIconDisplay();
});
function changeIconDisplay() {
if (input.value.trim() == "" ) {
icon.style.display = "none";
} else {
icon.style.display = "flex";
}
}
</script>
Related
I need to enable the submit button as soon as all input fields has value enterred. I have two input fields type text and type password and a button which is disabled (I set its class as "disabled" than use CSS to change color etc..), I would like to remove that class whenever the above condition is met. I added 'change' and 'input' event listeners to all field like below:
const inputs = [...document.querySelectorAll('input[type="text"], input[type="password"]')];
const continueBtn = document.querySelector('continuebtn');
const signinForm = document.querySelector('#sign-in-form');
inputs.forEach((input) => {
input.addEventListener('input', function(e){
if (input.value !== '') {
continueBtn.classList.remove('disabled');
}else{
continueBtn.classList.add('disabled');
}
}
});
Tried with e.target.value.trim() === '' as well
I guess the above would be applied to all inputs and check if they're empty when the user is typing, but I'm not able to make it work: the button is being activated no matter what I do.
I would need some help in plain Javascript as this is what I'm currently learning. no jQuery. Thanks
Use the every() method to check all the inputs, not just the one that the user is currently editing.
const inputs = [...document.querySelectorAll('input[type="text"], input[type="password"]')];
const continueBtn = document.querySelector('#continuebtn');
const signinForm = document.querySelector('#sign-in-form');
inputs.forEach((input) => {
input.addEventListener('input', function(e) {
if (inputs.every(input => input.value.trim())) {
continueBtn.classList.remove('disabled');
} else {
continueBtn.classList.add('disabled');
}
});
});
#continuebtn.disabled {
background-color: grey;
}
<input type="text">
<input type="password">
<button id="continuebtn" class="disabled">Continue</button>
I have this section of javascript in my html that grabs a form input, puts it through a function and returns a json. I then want to either hide or show certain form elements based on the values in this json.
At the moment, i can do all of this fine except for changing the style.display properties of the elements im trying to hide/show, i can find them okay with getElementbyId (have tested this with other stuff) but the changes i make to the style don't seem to do anything.
As you can see below, i have put in a few alerts to make sure everything is working, and they all seem to align with what i need from the function. The alert showing style.display even matches up with what i'm trying to change it to, however even if it says "none", the form element still shows up.
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
)
}
</script>
Edit: i added the console.log lines in but nothing seems to show in the console.
console log image
The issue was that the page was reloading to it's original state after the script had been executed, so i stopped this by adding "; return false" after the function like so:
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
); return false
}
</script>
having a bit of trouble.
im trying to creat a play again button the appears only when the user wins,
i've set the condition of the div to visibility:none when the user won,
else its in display:none
however, the button always appears, right from the start, any advice?
the audio plays correctly, only when the user wins.
so i got this piece of code in html:
<div id="Again">
<button type="button" onclick="toggle_visibility">Play Again</button>
</div>
and the following in js:
function toggle_visibility(id) {
var x = document.getElementById('Again');
if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
audioWin.play();
x.style.display = 'block';}
else {
x.style.display = 'none';
}
The initial display state of the button should be none. Here's a skeleton snippet that may help you along:
const button = document.querySelector("button");
const input = document.querySelector("input");
const inputHandler = evt => {
if (+evt.target.value == guessValue) {
button.classList.replace("hidden", "visible");
} else {
button.classList.replace("visible", "hidden");
}
};
let guessValue = Math.ceil(Math.random() * 10);
button.addEventListener("click", () => {
button.classList.replace("visible", "hidden");
input.value = "";
guessValue = Math.ceil(Math.random() * 10);
});
input.addEventListener("change", inputHandler);
input.addEventListener("keyup", inputHandler);
button.hidden {
display: none
}
button.visible {
display: inline-block
}
<input type="number" max="10" min="1"> Guess a number (1 - 10)
<button class="hidden">Again?</button>
The button is visible since the beginning because it has neither an "hardcoded" style attribute which says to hide it or a CSS proprerty which does the same. The JS code which "toggles" the button is only triggered when pressed, so it has no effect as the page loads.
I'm trying to change the text of a button when it's pressed with JavaScript. Should be very straightforward, however, it's not working. Can anyone explain? Here's my code:
function changeInnerHTML() {
var buttonValue = document.getElementById('elementTEST').innerHTML;
var buttonValueInnerHTMLBegin = '<p id="elementTEST">';
var buttonValueInnerHTMLEnd = '</p>';
alert("buttonValue = " + typeof(buttonValue)); // -> "string"
if (buttonValue == "Online") {
alert("turn off"); // -> "turn off"
buttonValue = buttonValueInnerHTMLBegin + "Offline" + buttonValueInnerHTMLEnd; // -> DOESN'T CHANGE ANYTHING
alert("turned off"); // -> "turned off"
} else if (buttonValue == "Offline") {
buttonValue = "Online";
} else {
alert("There's a problem");
}
}
<div class="containerTEST">
<div class="divTEST" onclick="changeInnerHTML()">
<p id="elementTEST">Online</p>
</div>
</div>
I have run this both with and without the "buttonValueInnerHTMLBegin/End" variables being included, and I get the same result.
I get the alerts (shown as comments in the code), but the text/innerHTML doesn't change.
Thanks for any help!
It's not a reference, you'll have to set it directly at the end:
document.getElementById('elementTEST').innerHTML = buttonValue
try this:
var buttonValue = document.getElementById('elementTEST');
function changeInnerHTML(){
if (buttonValue.innerHTML == "Online")
buttonValue.innerHTML= "Offline";
else if (buttonValue.innerHTML == "Offline")
buttonValue.innerHTML = "Online";
}
codepen: example
There's absolutely no reason to change the HTML. Change only the textContent
(Use Element.innerHTML = "bla" to set a new inner HTML)
Use Element.textContent = "bla" to set a new text content
Don't use inline JS onclick - it's discouraged for code maintainability reasons
Use a <button> for semantic reasons and accessibility
Here's a simpler version
[...document.querySelectorAll(".toggleOnline")].forEach( el =>
el.addEventListener("click", () => {
el.textContent = /online/i.test(el.textContent) ? "Offline" : "Online";
})
);
.toggleOnline {
border: none;
border-radius: 0;
background: #ddd;
padding: 8px 16px;
}
<button class="toggleOnline" type="button" aria-live="assertive" aria-atomic="true">
Online
</button>
Now you can also tab your element and use Spacebar or Enter to toggle your button.
I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});