I want to have an element visible only if another element's value is not empty.
Right now I'm doing this using:
function setReceiveSmsNotificationsCheckboxArea() {
var checkbox = $('#ReceiveSmsNotifications');
var value = !!$('#Cellphone').val().trim(); //bool depending on txt val
checkbox.prop('checked', value);
checkbox.closest('.form-group').toggle(value);
}
$('#Cellphone').change(function () {
setReceiveSmsNotificationsCheckboxArea();
});
$(document).ready(setReceiveSmsNotificationsCheckboxArea);
Is there a way to combine the two latter functions to one (so that the change even runs on startup as well?)
You can trigger the change event on page load in order to trigger the handler
function setReceiveSmsNotificationsCheckboxArea() {
var checkbox = $('#ReceiveSmsNotifications');
var value = !!$('#Cellphone').val().trim(); //bool depending on txt val
checkbox.prop('checked', value);
checkbox.closest('.form-group').toggle(value);
}
$('#Cellphone').change(setReceiveSmsNotificationsCheckboxArea).change();
Related
I have a web application which has an onchange event for loading multiple select options to a textbox separated by ',' and slice the last ','
It's working fine,
I have an another function for form filling. When I try to load the form only select option is being updated expecting onchange function to get data from select and have some value in textbox.
But sadly it's not working but working only after new option is selected or removed and added back
Function for adding multiple select data to textbox with onchange event:
// arguments: reference to select list, callback function (optional)
function getSelectedOptions(sel,fn) {
var opts = [], opt;
// loop through options in select list
for (var i=0, len=sel.options.length; i<len; i++) {
opt = sel.options[i];
// check if selected
if ( opt.selected ) {
// add to array of option elements to return from this function
opts.push(opt);
// invoke optional callback function if provided
if (fn) {
fn(opt);
}}}
// return array containing references to selected option elements
return opts;
}
// example callback function (selected options passed one by one)
function callback(opt) {
// display in textarea for this example
var display = document.getElementById('display');
display.innerHTML += opt.value + ',';
}
// anonymous function onchange for select list with id lstBox2
document.getElementById('sel1').onchange = function(e) {
// get reference to display textareaa
var display = document.getElementById('display');
display.innerHTML = ''; // reset
// callback fn handles selected options
getSelectedOptions(this, callback);
// remove ', ' at end of string
var str = display.innerHTML.slice(0, -1);
display.innerHTML = str;
};
Function to form filling:
$(document).ready(function () {
tests = split[testIndex];
// $('#display2').val(tests);
var opt2 = '<option selected>' + tests + '</option>';
$('#sel').append(opt2);})
Try moving your document.getElementById('sel1').onchange code into the $(document).ready(...) block. It's hard to tell without a complete page example, but one possibility is that 'sel1' isn't part of the DOM yet when you try to add the onchange handler.
Try to use
$('body').on('change', '#sel1', function(e) {
});
instead if the elements are added after load.
I have input in my page and it get or set value from other function in js
now i want know any ways has when my input get or set value it run other
function and set other input value
here is my function set value to input1
function showPoint(loc) {
var docloc = myDiagram.transformDocToView(loc);
var elt = document.getElementById("P18_LOC");
elt.value = "view coordinates: " + docloc.x.toFixed(2) + " " + docloc.y.toFixed(2);
}
now i need any event or listener when input get or set value run other function
i tired onchange() and oninput() and some more js event but i cant fix it
now : any way has to do that?
When an element gets its value changed dynamically through code, user events like change and input don't fire off. What you need to do is manually call for those events to fire with the jQuery .trigger() method.
function showPoint(loc) {
var docloc = myDiagram.transformDocToView(loc);
var elt = document.getElementById("P18_LOC");
elt.value = "view coordinates: " + docloc.x.toFixed(2) + " " + docloc.y.toFixed(2);
// Trigger the change event of the P18_LOC element
$(elt).trigger("change");
}
Now, you can set up a change event handler for P18_LOC and it will fire whenever showPoint() is called.
Can I attach any event handlers to HTML hidden input fields? Basically I want to run a function when a hidden input field value changes.
Events are only triggered when the user performs the event in the browser, so if it's <input type="hidden"> or an <input> hidden by CSS, the user won't be able to trigger events to your input.
The only way you would get onchange to work is if you manually trigger onchange in Javascript. A quick example of this:
<form name="f" onsubmit="document.f.h.value='1';
document.f.h.onchange();
return false;"
>
<input type="hidden" name="h" value="0" onchange="alert(document.f.h.value);" />
<input type="submit" />
</form>
Yes, certain browsers (such as Firefox) will fire an onclick or onfocus event on hidden elements when they're activated via an accesskey attribute (meant to provide a keyboard hotkey to jump to an input).
Open the below in firefox, focus the frame, then strike Alt+Shift+x (Windows and Linux) or Ctrl+Alt+x (Mac).
<input type="hidden" accesskey="x" onclick="alert('clicked!');" />
JavaScript has focus events for the elements. There are three focus events: focus, focusin, and focusout.
I discovered focusout will trigger when an element display state is change for both block and none, while focusin only triggered for display state of block.
document.getElementById('element_id').addEventListener('focusout',function(e){
if (this.style.display === "none") {
// perform operations when the element is hidden, like clear fields, etc.
} else {
// perform operations when the element is displayed, like populate fields
}
});
Facing the problem I needed to react on change of hidden inputs which were modified by code which was out of my control, I got inspired by JS onchange hack for input[type=hidden] and created following solution for my problem using MutationObserver
Request:
I want to have function FAM.processFields run whenever any of selected subset of form fields (expressionFields) changes its value.
Problem:
Some of the form fields are of type="hidden", so change event is never fired for them.
Solution:
var index, elementId, element;
var elementIdPrefix = g_form.getTableName() + ".";
var expressionFields = this.getExpressionFieldNames();
// As trigger either Event or MutationRecord is passed, depends on input type
var processFieldsCallback = (function(trigger) {
// Relies on instance of - FAM object - added in onLoad script
FAM.processFields();
});
var changeOfValueConfig = {attributeFilter: ["value"]};
var processFieldsObserver = new MutationObserver(processFieldsCallback);
if (this.debug) {
console.log("addChangeEventListeners to expressionFields");
console.log(expressionFields);
}
for (index = 0; index < expressionFields.length; index++) {
elementId = elementIdPrefix + expressionFields[index];
element = document.getElementById(elementId);
// In case of hidden input (e.g. glideList, fieldList, checkbox) we need to register an observer to it
if (element.getAttribute("type") && element.getAttribute("type").toLowerCase() == "hidden") {
processFieldsObserver.observe(element, changeOfValueConfig);
if (this.debug) {
console.log("register processFieldsObserver of changeOfValueConfig on elementId " + elementId);
console.log(element);
}
}
else {
element.addEventListener("change", processFields);
if (this.debug) {
console.log("addChangeEventListeners on elementId " + elementId);
console.log(element);
}
}
}
Facing the problem I needed to react on change of hidden inputs which were modified by code which was out of my control, I got inspired by JS onchange hack for input[type=hidden] and created following solution for my problem using MutationObserver
Request:
I want to have function FAM.processFields run whenever any of selected subset of form fields (expressionFields) changes its value.
Problem:
Some of the form fields are of type="hidden", so change event is never fired for them.
Solution:
var index, elementId, element;
var elementIdPrefix = g_form.getTableName() + ".";
var expressionFields = this.getExpressionFieldNames();
// As trigger either Event or MutationRecord is passed, depends on input type
var processFieldsCallback = (function(trigger) {
// Relies on instance of - FAM object - added in onLoad script
FAM.processFields();
});
var changeOfValueConfig = {attributeFilter: ["value"]};
var processFieldsObserver = new MutationObserver(processFieldsCallback);
if (this.debug) {
console.log("addChangeEventListeners to expressionFields");
console.log(expressionFields);
}
for (index = 0; index < expressionFields.length; index++) {
elementId = elementIdPrefix + expressionFields[index];
element = document.getElementById(elementId);
// In case of hidden input (e.g. glideList, fieldList, checkbox) we need to register an observer to it
if (element.getAttribute("type") && element.getAttribute("type").toLowerCase() == "hidden") {
processFieldsObserver.observe(element, changeOfValueConfig);
if (this.debug) {
console.log("register processFieldsObserver of changeOfValueConfig on elementId " + elementId);
console.log(element);
}
}
else {
element.addEventListener("change", processFields);
if (this.debug) {
console.log("addChangeEventListeners on elementId " + elementId);
console.log(element);
}
}
}
You can still trigger events on hidden input using labels
The accepted answer claims that: "The user won't be able to trigger events to your input.", but this is not true.
A label connected to an input element can also trigger an input, so even though the input element itself is hidden, if properly connected to a label the user can trigger the input by its label:
There are two ways to connect an input to a label,
Use the id of the input element in the for attribute:
<label for="checkbox">Label</label><input type="checkbox" id="checkbox"/>
Or simply wrap the input inside a label:
<label><input type="checkbox"/>Label</label>
See a working code example here in fiddle or below:
const onChange = (event) => {
console.log(event);
const checkbox = event.target;
alert("checkbox value is: " + checkbox.checked);
}
document.getElementById('checkbox').addEventListener('change', onChange);
input[type="checkbox"] {
visibility: hidden;
}
label {
font-weight: bold;
}
<label>
<input id="checkbox" type="checkbox"/>
label for hidden checkbox
</label>
I am having some problems with a javascipt function which I'm working on.
Here is what I am trying to do with the function:
I have a table element with a given value, and when there is a click on it, it calls my javasript function which is supose to appendChild an INPUT element with the value of the element, so the user can change that value. I want the INPUT element to call a function whit the onblur() event, so the modified value could be display again on the table element.
My problem is that the element does not respect the onblur() event. The function is executed right after the Input element is created, and does not wait to be an onblur() event.
Here is the code of the two functions:
var elemento = true;
function prueba(clave,cantidad) {
if(elemento){
var percent = document.getElementById('porciento' + clave);
percent.innerHTML = "";
var input = document.createElement("input");
input.setAttribute('type','text');
input.setAttribute('size','5');
input.setAttribute('value',cantidad);
input.setAttribute('id','child'+clave);
percent.appendChild(input);
input.focus();
child = document.getElementById("child" + clave);
child.onblur = blurPrueba();
}
}
function blurPrueba() {
if(elemento)
alert("Hello");
}
The alert is displayed without being an onblur()
Does anyone knows why this is happening???
Your problem is: child.onblur = blurPrueba(), where you execute blurPrueba immediately. Should be a reference: child.onblur = blurPrueba
Changing the line, you tell the browser: "on blur for the child element, activate the blurPrueba function".
If you use blurPrueba() you activate the function and assign it's result to the blur event, blurPrueba() doesn't return anything. So your line actually says: "onblur = undefined"
In summary, if you want the browser to handle an event (here blur) you need to provide a reference to the handler function (here blurPrueba).
Change
child.onblur = blurPrueba();
to
child.onblur = function(){blurPrueba()};
I'll keep this short - I've got a list of buttons, that I create using a loop, and when one of them gets clicked I want to be able to pass its id attribute to another file in order to dynamically generate a new page.
Here's the code:
for (var i in data.contacts) {
var temp = document.createElement('div');
temp.className = "contacts";
var dude = document.createElement('input');
dude.type = "button";
dude.value = data.contacts[i];
dude.id = data.contacts[i];
dude.className = "dude_button" + data.contacts[i];
dude.addEventListener('click', function(event) { gotoProfile(dude.id); }, false);
temp.appendChild(dude);
temp.appendChild(document.createElement('br'));
theDiv.appendChild(temp);
}
// and now in another file, there's gotoProfile():
function gotoProfile(x) {
var username = document.getElementById(x).value;
if (xmlHttp) {
try {
.... etc.
Now see this works, sort of, but the problem is that when I click any button, it only passes the last dude.id value from the list data.contacts. Obviously I want every button's addEventListener to pass its own data.contacts[i] value, instead of just the last one.
Help appreciated, thanks guys.
Because JavaScript has no block scope, dude will refer to the last assigned element (because the loop finished) when the event handler is called. You have to capture the reference to the current dude by e.g. using an immediate function:
dude.addEventListener('click', (function(d) {
return function(event) {
gotoProfile(d.id);
}
}(dude)), false);
This is a common error when creating functions in a loop.
But you can make it even easier. The event object has a property target that points to the element the event was raised on. So you can just do:
dude.addEventListener('click', function(event) {
gotoProfile(event.target.id);
}, false);
And with that said, you don't need to add a handler for every button. As you are doing the same for every button, you could attach the same event handler above to the parent of the buttons (or a common ancestor) and it would still work. You just have to filter out the clicks that don't happen on a button:
parent.addEventListener('click', function(event) {
if(event.target.nodeName == 'INPUT' && event.target.type == "button") {
gotoProfile(event.target.id);
}
}, false);