here's my code:
document.getElementById("frequencyweekly").checked = function() {
document.getElementById("newsoptions").className = "activesubscription";
};
<div id="newsoptions">
<input type="radio" id="frequencyweekly" name="newsletterfrequency">
<label for="frequencyweekly">Weekly</label>
<input type="radio" id="frequencymonthly" name="newsletterfrequency">
<label for="frequencymonthly">Monthly</label>
</div>
I would like my .newsoptions div have class .activesubscription if #frequencyweekly button is checked. How should I do that?
checked is a boolean, not an event that fires a function, so you probably want
if ( document.getElementById("frequencyweekly").checked ) {
document.getElementById("newsoptions").className = "activesubscription";
}
if you want that in an event handler it would be
var box = document.getElementById("frequencyweekly"),
elem = document.getElementById("newsoptions");
box.addEventListener('change', function() {
if ( this.checked ) {
elem.classList.add("activesubscription");
} else {
elem.classList.remove("activesubscription");
}
}, false);
If you want to do something when clicking a box, you use the onclick attribute. Within that, you can check the checked property.
document.getElementById("frequencyweekly").onclick = function() {
if (this.checked) {
document.getElementById("newsoptions").className = "activesubscription";
} else {
document.getElementById("newsoptions").className = "";
}
}
Related
I've looked through numerous topics regarding this, but none of the solutions are fitting my need. I need to enable the submit button only if there is data going to be submitted, and disable it again if there is no data.
$("input").each(function() {
$(this).keyup(function() {
console.log("keyup event fired");
$("input").each(function() {
if ( $(this).val() !== "" ) {
empty = false;
} else {
empty = true;
}
});
if ( empty ) {
$("#download-project").addClass("isDisabled");
$("#download-project").click(function(e) {
e.preventDefault();
});
} else {
$("#download-project").removeClass("isDisabled");
$("#download-project").click(function(e) {
e.preventDefault();
$(".editor-form").submit();
});
}
});
});
My current code only enables the button, and than the if the user deletes the data, it doesn't disable the button. Looking at the console it also seems keyup is only firing once.
JSFiddle
You can add an input event listener to each of the input tags, which will fire when the value has been changed, and check if any of the input tags has a value that is only spaces.
const inputs = $('input'), downloadBtn = $('#download-project');
inputs.on('input', function(e){
var invalid = inputs.is(function(index, element){
return !$(element).val().trim();
});
if(invalid){
downloadBtn.addClass("isDisabled").prop("disabled", true);
} else {
downloadBtn.removeClass("isDisabled").prop("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
First Name: <input type="text"/><br/>
Last Name: <input type="text"/><br/>
Age: <input type="number"/><br/>
<button id="download-project" type="submit" disabled>
Submit
</button>
</form>
Try to put change event listener instead of keyup.
$("input#submit").prop("disabled", true);
let isOk = true;
$("input").change(function (){
$("input").each(()=>{
console.log(this);
if($(this).val() === "") {
isOk = false;
}
});
if(isOk) $("input#submit").prop("disabled", false);
})
Test: https://codepen.io/Opalecky/pen/xxwWmyJ
I have a textbox which needs to be filled with website URL. So when user places the cursor in the textbox then the textbox should prefill with "http://" (Not a placeholder).
If the user does not enter anything and moves to the next textbox then the textbox have empty value
If the user fills the textbox then the value is unchanged
I tried below Javascript code but did not work:
if (document.activeElement.id == 'input-textbox-id' && !document.activeElement.value) {
document.querySelector("#input-textbox-id").value="http://";
} else if (document.activeElement.id != 'input-textbox-id' && (!document.activeElement.value || document.activeElement.value == 'http://')) {
document.querySelector("#input-textbox-id").value="";
}
You can use the focus and blur events for this.
Assuming that the variable textBox contains the reference to your textBox element, you can use the following code:
let textBox = document.getElementById("a");
textBox.addEventListener("focus", function() {
if (!this.value) {
this.value += "http://";
}
});
textBox.addEventListener("blur", function() {
if (this.value == "http://") {
this.value = "";
}
});
<input type="text" id="a">
You will need to attach event listener by using addEventListener. Events you need: focus and focusout.
We add .http-prefill class for all inputs. We iterate over inputs array and attach event.
Please do not forget to remove eventListener when you are done eg. you unload the form.
To do so, just copy the code for adding listeners and replace addEventListener with removeEventListener.
inputs.forEach(function(input) {
input.removeEventListener('focus', onFocus);
input.removeEventListener('focusout', onFocusOut);
});
Example code:
var fillValue = 'http://';
var onFocus = function() {
this.value = fillValue;
}
var onFocusOut = function() {
if (this.value === fillValue) {
this.value = '';
}
}
var inputs = document.querySelectorAll('.http-prefill');
inputs.forEach(function(input) {
input.addEventListener('focus', onFocus);
input.addEventListener('focusout', onFocusOut);
});
.http-prefill {
width: 100%;
margin-bottom: 5px;
}
<input class="http-prefill" name="input-0" />
<input class="http-prefill" name="input-1" />
<input class="http-prefill" name="input-2" />
<input class="http-prefill" name="input-3" />
you can use some key events like onKeyDown and when keydown you can get hold of old value and append it with new value.
let keyPressed = true
function onKeyDown(event) {
if(keyPressed && event.keyCode !== 8)
{
keyPressed = false;
let oldvalue = document.getElementById('input-textbox-id').value;
document.getElementById('input-textbox-id').value = "http://"+oldvalue
}
if(!document.getElementById('input-textbox-id').value)
{
keyPressed = true;
}
}
here is working code. http://jsbin.com/zoxiwokepi/edit?html,output
Basically I have two divs,
<div id="firstPage"></div>
and
<div id="details">
<div id='searchBox' class='detail--searchBox'>
<input id='txtSearchTerm' name='txtSearchTerm' type='text'>
</div>
</div>
On page load the textbox with id searchBox is hidden and it is shown on click event of div with id firstPage. I have following function which must be triggered on textbox change. But this input event is triggered once page is reloaded.
onSearchBoxOnDetailsChange: function () {
$("#searchBox").on("input", "#txtSearchTerm", function () {
var val = $(this).val().trim();
val = val.replace(/\s+/g, '');
if (val.length > 1) {
console.log(val);
} else {
}
});
},
Write your code like below:
onSearchBoxOnDetailsChange: function () {
$(document).on("input", "#searchBox #txtSearchTerm", function () {
var val = $(this).val().trim();
val = val.replace(/\s+/g, '');
if (val.length > 1) {
console.log(val);
} else {
}
});
},
In my code, I am setting a change listener on my checkboxes here
$(".section").change(function() {
if($(this).is(":checked")) {
$("." + this.id).show();
...
Now I am trying to do a "code-driven" click on the checkbox, and I have
$(".secTitle").click(function(e) {
var elem = this;
while(elem) {
if (elem.className && elem.className.indexOf ('DOC_SECTION') != -1) {
var clzes = elem.className.split(" ");
var clzIdx = 1;
if (elem.getAttribute('closeSecClassIdx')) {
clzIdx = parseInt(elem.getAttribute('closeSecClassIdx'));
}
var chk = document.getElementById(clzes[clzIdx]);
chk.checked = false;
alert(chk.onchange);
//chk.changed();
break;
}
else {
elem = elem.parentNode;
}
}
});
I know that I have the right element, as chk.checked = false; is working correctly. After that I'm trying to invoke the change method set earlier but my alert is showing 'undefined'.
You can trigger the change event by calling $(chk).change(). Below I've created a little prototype that shows binding to the change event and invoking it.
jQuery(function($) {
// bind to the change event
$("input").change(function() {
console.log('change triggered!');
});
// now trigger it
$("input").change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
This is my first real dive into javascript. I've been going at this for hours and haven't found a solution (though I learned a lot).
<script type="text/javascript">
function changeClass(){
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function()
{
document.getElementById("switcher").addEventListener( 'click' , changeClass );
}
</script>
Here is the HTML:
<div class="switch switch-blue" id="switcher">
<input type="radio" class="switch-input" name="resp" value="1" id="respyes" checked>
<label for="respyes" class="switch-label">YES</label>
<input type="radio" class="switch-input" name="resp" value="2" id="respno">
<label for="respno" class="switch-label">NO</label>
</div>
The default is a blue background. If they choose no I want it red, then back to blue if they click yes, all that is in the css. If I manually change the class from switch-blue to switch-red, it works. Right now it does absolutely nothing.
Thank you!
Problem here is event propagation when an internal element click event bubbleup so it causing calling your function twice which change class and then revert back so try:
function changeClass(event) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
if (window.event != undefined) window.event.cancelBubble = true;
event.stopPropagation();
}
window.onload = function () {
document.getElementById("switcher").addEventListener('click', changeClass);
}
event.stopPropagation(); will stop this bubbling and for IE use window.event.cancelBubble = true;
Here is working JSFiddle
Edit
But this will not guarentee the change of class on radio button click as event is bind to parent div so clicking over div anywhere will trigger the event, so try to bind event on the radio-buttons:
Event on Radio click
function changeClass(clickedItem) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (clickedItem == 1) {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function () {
var yes = document.getElementById('respyes');
var no = document.getElementById('respno');
yes.onclick = function () {
changeClass(2)
};
no.onclick = function () {
changeClass(1)
};
}
function changeClass(elem){
var currentClass = elem.className, blueClass = "switch switch-blue",
redClass= "switch switch-red"
elem.className = (currentClass == blueClass) ? redClass:blueClass;
}
window.onload = function()
{
document.getElementById("switcher").onclick = function(){
changeClass(this);
};
}
JS Fiddle: http://jsfiddle.net/dYt8v/
Looks like it is working fine, when you add the css classes.
Here is a demo. I think you are missing the styles.
Add the style to your head and see if that works for you.
<style>
.switch-blue{
background:blue;
color:#fff;
}
.switch-red{
background:red;
color:#fff;
}</style>
Feel free to change the styles as you need them.
Edit
I just noticed that you have the event listeners attached to the div instead of the radio button. That will change the background when you click the div, instead of the buttons. See this updated fiddle.