Control javascript hide/show div with radio controls without jquery - javascript

The code below doesn't seem to work
//javascript
function t_show() {
if(document.getElementById("t_show").checked == true){
if(document.getElementById("t_show").value == 1) {
showDiv("t_settings");
}
} else {
hideDiv("t_settings");
}
}
function show(show){
var s = document.getElementById(show);
if(!s) return true;
s.style.display="";
return true;
}
function hide(hide){
var h = document.getElementById(hide);
if(!h) return true;
h.style.display="none";
return true;
}
//html
Text show:
<input type="radio" name="t_show" value="1" checked="checked" onchange="t_show(); update_preview();" id="t_show">Yes
<input type="radio" name="t_show" value="0" onchange="t_show(); update_preview();" id="t_show">No
<div id="t_settings">This content is to be shown if the show text is enabled.</div>

You <div/> has a class of t_settings but you are calling getElementById()
You are calling showDiv() but the function name is actually show()
You are calling hideDiv() but the function name is actually hide()
Instead of doing s.style.display = ""; use s.style.display = "block";
document.getElementById("t_show").value == 1 will always be true, you can just simplify it to use document.getElementById("t_show").checked
An id needs to be unique per the dom. there should only be one t_show per page.
Putting all that together you end up with this:
function showDiv(show) {
var s = document.getElementById(show);
if (!s) {
return true;
}
s.style.display = "block";
return true;
}
function hideDiv(hide) {
var h = document.getElementById(hide);
if (!h) {
return true;
}
h.style.display = "none";
return true;
}
function t_show() {
if (document.getElementById("t_show").checked) {
showDiv("t_settings");
}
else {
hideDiv("t_settings");
}
}
Code example on jsfiddle.

You have a few problems there. Mark already pointed out most of the obvious ones. I'd add that you should always have just one element with a unique ID (even radio buttons).
Also, you don't need two JavaScript functions for the (almost) same activity.
I'd suggest this:
HTML:
Text show:
<input type="radio" name="t_show" value="1" checked="checked" onchange="t_show(); update_preview();" id="t_show_yes">Yes
<input type="radio" name="t_show" value="0" onchange="t_show(); update_preview();" id="t_show_no">No
<div id="t_settings">This content is to be shown if the show text is enabled.</div>
JS:
function t_show() {
if(document.getElementById("t_show_yes").checked == true)
setDisplay("t_settings", "");
else
setDisplay("t_settings", "none");
}
function setDisplay(id, value){
var o = document.getElementById(id);
if(!o)
return false;
o.style.display = value;
return true;
}
Example on jsFiddle: http://jsfiddle.net/ZptpP/
EDIT - As requested in the comments:
You could modify the t_show function to send an array of IDs to be hidden/displayed.
function t_show() {
var elements = new Array("t_settings","div1","div2");
if(document.getElementById("t_show_yes").checked == true)
setDisplay(elements, "");
else
setDisplay(elements, "none");
}
function setDisplay(elements, value){
var o;
for (var i = 0; i < elements.length; i++) {
o = document.getElementById(elements[i]);
if (o != undefined)
o.style.display = value;
}
return true;
}
See the updated fiddle: http://jsfiddle.net/ZptpP/1

In your show function, change...
s.style.display="";
to
s.style.display="block";

why don't invoke method "t_show()" with a boolean parameter like:
t_show(true);// for input with value = 1
...
t_show(false);// for input with value = 0
and function:
t_show(value) {
if(value == true){
showDiv("t_settings");
} else {
hideDiv("t_settings");
}
}
function showDiv(show){ }
function hideDiv(show){ }
so you don't need to check value...
bye

Related

Kendo Validator always says multi-select is invalid

I have a multiselect that is dynamically created and appended to a template with the following bit of code:
if(fieldMap[i].required == true){
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'*</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" name="'+fieldMap[i].fieldName.toLowerCase()+'" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'">';
} else{
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'">';
}
optString = '';
for(var k = 0; k < fieldMap[i].picklistVals.length; k++){
if(k == 0){
optString += '\''+fieldMap[i].picklistVals[k]+'\'';
}
else{
optString += ',\''+fieldMap[i].picklistVals[k]+'\'';
}
}
//Close the input component as well as the container div
dynamicComponent += optString + ']"/>\n<span class="k-invalid-msg" data-for="'+fieldMap[i].fieldName.toLowerCase()+'"></span></div>\n\n';
I run a validator.validate() on save button click to determine if information should be saved or not, which is dependent on if the multi-select input is required.
This pops up the invalid tooltip message when nothing is selected just fine. The issue is, however, that it will be marked invalid even if a selection is made. I am wondering if anyone has any solutions for how to get a validator to work correctly with the multiselect. Just hiding the pop ups is not really what I am after, as the validate() function will still fail even if the pop up is hidden, and I need the validate() function to pass.
Maybe not the best, but here is what I got.
function Save(){
$("#divTenureContainer .k-invalid").removeClass("k-invalid");
var tenureChecked = $("#chkTenure").prop('checked');
var tenureValid = Configuration_Tenure_Validator.validate();
}
Configuration_ValidateInput = (input) => {
var validationType = $(input).data("validation");
var required = $(input).prop("required") || $(input).hasClass("js-required");
if (!required) return true;
if (validationType) {
if (validationType === "stars") {
return $(input).val() > "0";
}
if (validationType === "hashtags") {
return ($(input).data("kendoMultiSelect").value().length > 0);
}
if (validationType === "required-text") {
return $(input).val() >= "";
}
}
return true;
}
var Configuration_ValidationRules = { rules: { Configuration_ValidateInput }, validationSummary: false };
var Configuration_Tenure_Validator = $("#divTenureContainer").kendoValidator(Configuration_ValidationRules).data("kendoValidator");

Add different event listener to a set of elements in a loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
Hello people of the internet,
I have a set of buttons and if a button is clicked it's content should be appended to a text field's content.
Lets say I have three buttons: [first] [second] [third]
My addEventListener-implementation results in "third" appended to the in text field's content, regardless which button I press. I don't know hot to fix this.
function setupListeners() {
var targetInputField = d.querySelector("#expression");
var t = d.querySelectorAll(".expression-button").length;
for (var i = 1; i <= t; i++) {
var btnElem = d.querySelector("#expression-button-"+i);
btnElem.addEventListener('click', function() {
if (targetInputField.value == "") {
targetInputField.value = btnElemLocal.innerText;
}
else {
targetInputField.value += ";"+btnElemLocal.innerText;
}
});
}
}
What I want:
If I click all of the three buttons in a row, the text field's content should be :
"first;second;third"
And not :
"third;third;third"
Put the click event code inside another function (btnClick in my example) and just call it when you attach the event in .addEventListener() inside the loop, then use this to refer to the current clicked element :
function btnClick() {
var targetInputField = d.querySelector("#expression");
if (targetInputField.value == "") {
targetInputField.value = this.innerText;
}
else {
targetInputField.value += ";"+this.innerText;
}
}
Hope this helps.
var d = document;
function setupListeners() {
var t = d.querySelectorAll(".expression-button").length;
for (var i = 1; i <= t; i++) {
var btnElem = d.querySelector("#expression-button-"+i);
btnElem.addEventListener('click', btnClick);
}
}
function btnClick() {
var targetInputField = d.querySelector("#expression");
if (targetInputField.value == "") {
targetInputField.value = this.innerText;
}
else {
targetInputField.value += ";"+this.innerText;
}
}
setupListeners();
<button class='expression-button' id='expression-button-1'>First</button>
<button class='expression-button' id='expression-button-2'>Second</button>
<button class='expression-button' id='expression-button-3'>Third</button>
<input id='expression' />

placeholder javascript fallback for textarea not working

The below is the html code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Please help me point out the mistake. placeholder fallback functionality is not working.I have been debugging it from long time.
Below is the link for fiddle:
check the functionality in ie9 and below as they doesn't support placeholder attribute:
http://jsfiddle.net/DxcYW/
Thanks
Here it is in pure JavaScript:
(function (D, undefined) {
'use strict';
var i, length, placeholder, textareas;
function hidePlaceHolder (placeholder) {
return function (e) {
var target;
target = e.target || e.srcElement;
if (target.value === placeholder) {
target.value = '';
}
};
}
function showPlaceHolder (placeholder) {
return function (e) {
var target;
target = e.currentTarget || e.srcElement;
if (target.value === '') {
target.value = placeholder;
}
};
}
if (! ('placeholder' in D.createElement('textarea'))) {
textareas = D.getElementsByTagName('textarea');
length = textareas.length;
for (i = 0; i < length; i += 1) {
placeholder = textareas[i].getAttribute('placeholder');
textareas[i].value = placeholder;
if (textareas[i].addEventListener) {
textareas[i].addEventListener('focus', hidePlaceHolder(placeholder));
textareas[i].addEventListener('blur', showPlaceHolder(placeholder));
} else {
textareas[i].attachEvent('onfocus', hidePlaceHolder(placeholder));
textareas[i].attachEvent('onblur', showPlaceHolder(placeholder));
}
}
}
}(document));
try putting your JS in
<script> ... </script>
tags. :)
My findings and solution:
Input fields have value attribute but TEXTAREA doesn't have it.
So when we use inputObj.defaultValue="sometext" for input tag it sets the default value as well as current value to sometext, if we dont define the attribute value="something" in the input tag.This works fine from ie9 and above. For below versions if we don't define value="sometext" inputObj.defaultValue="sometext" won't set current value as the default value by itself. For this we can do two things:
we have to manually give value="something which is equal to placeholder text"
we can get the value of placeholder through javascript and set the value from there.
This is not the case with textarea. Textarea doesn't have a attribute value. So when we use textareaObj.defaultValue="sometextarea text" then the default value is set to the given text but not the value itself as we don't have value attribute.value in textarea is nothing but the content between the textarea tags.
Difference between defaultvalue and value:
default value remains the same once it is set.
value is the current value which is being modified by javascript or ourself my typing into the textfield.
For my above issue I found a workaround just by adding one more line to my code:
<textarea name="test" rows="5" cols="20" placeholder="Brief description of your requirement,project, concept or idea"></textarea>
<script>
$(function() {
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
if (!supports_input_placeholder()) {
var fields = document.getElementsByTagName('textarea');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('placeholder')) {
fields[i].defaultValue = fields[i].getAttribute('placeholder');
fields[i].value = fields[i].getAttribute('placeholder');//setting the value
fields[i].onfocus = function() {
if (this.value == this.defaultValue)
this.value = '';
}
fields[i].onblur = function() {
if (this.value == '')
this.value = this.defaultValue;
}
}
}
}
});
</script>
Thank you guys for your quick replies and I pity the guy who voted down the question. I feel it is a good question. isn't it ?

Jquery form get default values

If I have code like this:
<form id="test_form">
<input type="text" value="Original value" />
</form>
Then using jQuery I run this code:
$('#test_form input').val('New value');
So input have new value, but I wanna get the old one, so I do:
$('#test_form')[0].reset();
now $('#test_form input').val() == 'Original value';
But reset method reset all form inputs and restore there default values, so how can I restore default value just in definite input?
on jQuery 1.6+
$('#test_form input').prop('defaultValue');
on older versions use .attr() instead of .prop()
You can use the defaultValue property:
this.value = this.defaultValue;
For example, the following code would reset the field to its default value when the blur event is fired:
$("#someInput").blur(function() {
this.value = this.defaultValue;
});
And here's a working example.
You could very easily build a plugin to do this, using the defaultValue property, which corresponds to the original state of the element.
$.fn.reset = function() {
this.each(function() {
this.value = this.defaultValue;
});
};
You can then call this plugin like this:
$('someSelector').reset();
Try whatever the jQuery equivalent to JavaScript's .getAttribute('value') is - the attribute does not change even if the value itself does.
I would suggest using placeholder attribute for inputs and textareas.
// Sample Usage
// $(document).ready(function(){ $.snapshot("#myForm"); }); Take shapshot
// event, function(){ $.reset("#myForm"); } Rest Form On Some Event
(function($) {
$.fn.getAttributes = function() {
var attributes = {};
if(!this.length)
return this;
$.each(this[0].attributes, function(index, attr) {
attributes[attr.name] = attr.value;
});
return attributes;
}
})(jQuery);
(function($)
{
jQuery.snapshot = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
if(elements && elements.length)
{
elements.each(function(){
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
var safe_attributes = {};
for(i in attributes)
{
var jq_attr = $(this).attr(i);
if(jq_attr != "undefined")
{
safe_attributes[i] = jq_attr;
}
}
if(tagName == "select")
{
var option = $(this).find("option:selected");
if(option && option.length)
{
var init_selected = option.attr("value");
safe_attributes['init_selected'] = init_selected;
}
}
if(tagName == "textarea")
{
var init_value = $(this).val();
safe_attributes['init_value'] = init_value;
}
$.data( $(this).get(0), "init_attr", safe_attributes );
});
}
}
jQuery.reset = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
var reset_btn = $('<input type="reset" name="reset" />');
form.append(reset_btn);
reset_btn.trigger("click");
reset_btn.remove();
if(elements && elements.length)
{
elements.each(function(){
var init_attributes = $(this).data("init_attr");
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
for(i in attributes)
{
if(i.toLowerCase() == "value" || i.toLowerCase() == "checked" || i.toLowerCase() == "selected")//if(i.toLowerCase() != "type")
{
var attr_found = false;
for(a in init_attributes)
{
if(i == a)
{
$(this).attr(a, init_attributes[a]);
attr_found = true;
}
}
if(!attr_found)
{
$(this).removeAttr(i);
}
}
}
if(tagName == "select" && 'init_selected' in init_attributes)
{
$(this).find("option:selected").removeAttr("selected");
var option = $(this).find("option[value="+init_attributes['init_selected']+"]");
if(option && option.length)
{
option.attr("selected", "selected");
}
}
if(tagName == "textarea")
{
if('init_value' in init_attributes)
{
$(this).val(init_attributes['init_value']);
}
}
$(this).trigger("change");
});
}
}
})(jQuery);

Javascript IE7/IE8 Discrepancy

When I use document.getElementById('checkbox1').checked == true in IE8 it does not work but works in IE7, any solutions please?
<script language="Javascript" type="text/javascript">
function swap(){
if(document.getElementById('checkbox1').checked == true ){
document.getElementById('captionrow1').style.display = "none";
document.getElementById('captionrow2').style.display = "inline";
document.getElementById('show').style.display = "inline";
if (location.href.indexOf("CheckBox1=1") == -1)
location.href = "employees_commends1a.asp?CheckBox1=1";
}
if(document.getElementById('checkbox1').checked == false ){
document.getElementById('captionrow1').style.display = "inline";
document.getElementById('captionrow2').style.display = "none";
document.getElementById('show').style.display = "none";
}
}
</script>
Make sure the checkbox has a unique ID Also your code changes the location = unloads the page - I am sure that is what makes your code not work.
I suggest this instead:
window.onload=function() {
var chk = document.getElementById('checkbox1');
chk.checked=location.href.indexOf("CheckBox1=1") != -1
chk.onclick=function() {
location = "employees_commends1a.asp?"+(this.checked?"CheckBox1=1":"CheckBox1=0");
}
swap();
}
function swap(){
var checked = document.getElementById('checkbox1').checked;
document.getElementById('captionrow1').style.display = (checked)?"none":"inline";
document.getElementById('captionrow2').style.display = (checked)?"inline":"none";
document.getElementById('show').style.display = (checked)?"inline":"none";
}
<input type="checkbox" id="checkbox1" />

Categories