Dynamically changing the view with Javascript - javascript

I am trying to do a simple task.
I have a button on a page
I click the button and it shows a label and an HTML select drop-down list.
Whenever I change drop-down list value, the label should change.
The code is below. Whenever I run it, it the label just changes once and the options tab never changes.
$(document).ready(function() {
showButton();
});
function showButton() {
//draw button
var $button = '<button type="button" id= "button">Button</button>';
$('.div1').after(button);
//add event listener on click
document.getElementById("thebutton").addEventListener("click",showLabel());
}
function showLabel() {
var label = "one";
var option = document.getElementById("options").value;
if(option == "one") {
label = "one";
}
if(option == "two") {
label = "two";
}
if(option == "two") {
label = "three";
}
var selectOptions = '<div align ="right"><select id="options"><option value="one">one</option><option value="two">two</option><option value="three">three</option></select></div>';
document.getElementById("container").innerHTML = selectOptions+ label;
document.getElementById("options").addEventListener("change", function(){
console.log('changed option');
showLabel();
});
}
Any ideas?

Edit:
<script>
$(document).ready(function() {
$('.div1').append('<button type="button" onclick="javascript:showLabel()" id="button">Button</button>');
$('.container').append('<div><select id="options"><option value="1">one</option><option value="2">two</option><option value="3">three</option></select></div>');
});
function showLabel() {
var option = document.getElementById("options").value;
if (option == 1) {
labelVal = 'one';
} else if (option == 2) {
labelVal = 'two';
} else if (option == 3) {
labelVal = 'three';
}
if (document.getElementById('label') != null) {
$('#label').val(labelVal);
} else {
$('.container').append('<input type="text" id="label" value="' + labelVal + '">');
}
}
</script>
<div class="div1"></div>
<div class="container"></div>

Related

JavaScript .click doesnt work in IE 11

I have been trying to get this code working for multi select option sets for dynamic crm. My problem here is that this code works effortlessly in Chrome, does exactly what I want it to but in IE the .click event returns false no matter what, if the check boxes are checked or unchecked.
All this code does is take a option set and converts it to a multi select list and sets value into the two fields "l1s_trainingmodulesvalues" holds the value of the option selected and "l1s_trainingmodules" holds the label of the option selected.
Can some one have a look at what I have been doing wrong.
<html><head>
<title></title>
<script src="../WebResources/new_jquery3.1.1.min.js" type="text/javascript"></script>
<script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
<script type="text/javascript">
// function will be called when web resource is loaded on Form.
$(document).ready(function ()
{
ConvertDropDownToCheckBoxList();
});
//Coverts option list to checkbox list.
function ConvertDropDownToCheckBoxList()
{
var dropdownOptions = parent.Xrm.Page.getAttribute("l1s_trainingmodulesoptionset").getOptions();
var selectedValue = parent.Xrm.Page.getAttribute("l1s_trainingmodulesvalues").getValue();
$(dropdownOptions).each(function (i, e)
{
var rText = $(this)[0].text;
var rvalue = $(this)[0].value;
var isChecked = false;
if (rText != '')
{
if (selectedValue != null && selectedValue.indexOf(rvalue) != -1)
isChecked = true;
var checkbox = "<label><input type=\"checkbox\" name =\"r\">" + rText + "<br></label>"
$(checkbox)
.attr("value", rvalue)
.attr("checked", isChecked)
.attr("id", "id" + rvalue)
.on('click',function ()
{
//To Set Picklist Select Values
var selectedOption = parent.Xrm.Page.getAttribute("l1s_trainingmodulesvalues").getValue();
alert($(this).is(':checked')); /*** This value always returns false in IE but in Chrome it works perfectly*/**
if ($(this).is(':checked'))
{
if (selectedOption == null)
selectedOption = rvalue+"";
else
selectedOption = selectedOption + "," + rvalue
}
else
{
var tempSelected = rvalue + ",";
if (selectedOption != null)
{
if (selectedOption.indexOf(tempSelected) != -1)
selectedOption = selectedOption.replace(tempSelected, "");
else
selectedOption = selectedOption.replace(rvalue, "")
}
}
//alert(rvalue);
parent.Xrm.Page.getAttribute("l1s_trainingmodulesvalues").setValue(selectedOption);
//To Set Picklist Select Text
var selectedYear = parent.Xrm.Page.getAttribute("l1s_trainingmodules").getValue();
if ($(this).is(':checked'))
{
if (selectedYear == null)
selectedYear = rText+"";
else
selectedYear = selectedYear + "," + rText
}
else
{
var tempSelectedtext = rText + ",";
if (selectedYear != null)
{
if (selectedYear.indexOf(tempSelectedtext) != -1)
selectedYear = selectedYear.replace(tempSelectedtext, "");
else
selectedYear = selectedYear.replace(rText, "");
}
}
//alert(selectedYear);
parent.Xrm.Page.getAttribute("l1s_trainingmodules").setValue(selectedYear);
})
.appendTo(checkboxList);
}
});
}
</script>
<meta charset="utf-8">
</head><body style="-ms-word-wrap: break-word;"><form><div id="checkboxList">
</div></form>
</body></html>
Your checkbox variable does not refer to a checkbox element. It's a label (var checkbox = "<label><input type=\"checkbox\" name =\"r\">" + rText + "<br></label>"), which does not have a checked state.
Inside your click handler, change
if ($(this).is(':checked'))
to
if ($(this).find('input').is(':checked'))

Jquery selectbox strong tag help required

I am using Jquery NiceSelect Plugin for my select boxes but I want a little change in it i.e.
I want to use the strong or b tag in options but this plugin automatically converts html into
<label class="nice_label">Some Text Etc</label>
and into this
<p class="top">Some Text Etc</p>
but I want to exclude the conversion of strong tag or bold tag so that it would work like this
<label class="nice_label">Some Text <strong>Etc</strong></label>
Here is my JS
(function ( $ ) {
$.fn.niceselect = function()
{
return this.each(function(index,value)
{
/*SET VARIABLES
============================*/
var name = $(this).attr('name')
var select = $(this);
var num = index;
var multi = false;
var multix = '';
var type= 'radio';
var required = '';
var classes = '';
var selected = '';
var placeholder = 'Select';
if(select.attr('multiple') !== undefined)
{
multi = true;
multix = '[]';
type= 'checkbox';
}
if($(this).attr('class') !== undefined)
{
var classes = $(this).attr('class');
}
if(select.find('[value="placeholder"]').length > 0)
{
placeholder = select.find('[value="placeholder"]').html();
}
if(typeof( select.attr('required') ) != 'undefined')
{
required = 'required';
}
/*WRAP SELECT IN DIV
-------------------------*/
select.wrap('<div class="select_style '+classes+'"/>');
$('<span class="selectcon"> </span>').insertBefore(select);
/*CREATE PLACEHOLDER + OPTION BOX
--------------------------------------------*/
$('<div class="niceselect '+name+'" data-multi="'+multi+'"><p class="top">'+placeholder+'</p><div class="value_wrapper"></div></div>').insertBefore(this)
/*CREATE OPTGROUP BOXES
--------------------------------------------*/
if(select.find('optgroup').length > 0)
{
select.find('optgroup').each(function(key, opt){
select.siblings('.niceselect').children('.value_wrapper').append('<div class="opt opt'+key+'"><span class="optTitle">'+$(opt).attr('label')+'</span></div>')
$(opt).find('option').each(function(index,value){
var val;
if($(this).val() == '')
{
val = $(this).html();
}
else
{
val = $(this).val();
}
var txt = $(this).html();
selected = '';
if(typeof( $(this).attr('selected') ) != 'undefined')
{
selected = 'checked';
select.siblings('.niceselect').find('p.top').html(txt)
}
select.siblings('.niceselect').find('.opt'+key).append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" >'+txt+'</label></div>')
})
})
}
/*CREATE GENERAL OPTION FIELDS*/
else
{
select.find('option').each(function(index,value){
var $this = $(this);
var val;
if($(this).val() == '')
{
val = $(this).html();
}
else
{
val = $(this).val();
}
var txt = $(this).html();
selected = '';
if(typeof( $(this).attr('selected') ) != 'undefined')
{
selected = 'checked';
select.siblings('.niceselect').find('p.top').html(txt)
}
select.siblings('.niceselect').children('.value_wrapper').append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" >'+txt+'</label></div>')
})
}
select.remove()
select.attr('name','blobla')
/*BIND CLICK FUNCTIONS (hide / show menu)
===========================================*/
$('body').on('click',function()
{
$('.niceselect .value_wrapper').hide();
$('.select_style').removeClass('active')
})
$('body').on('click','.niceselect',function(e)
{
e.stopImmediatePropagation();
if($(this).parent().hasClass('active'))
{
$(this).find('.value_wrapper').hide();
$(this).parent().removeClass('active');
console.log('here')
}
else
{
//$('.niceselect .value_wrapper').hide();
$(this).children('.value_wrapper').show()
$(this).parent().addClass('active')
}
})
/*BIND CLICK FUNCTIONS (check values / update visual)
=====================================================*/
$('body').on('click','.niceselect .value_wrapper .values',function(e){
e.stopImmediatePropagation();
var checkBoxes = $(this).find('input');
var par = $(this).parent().parent();
if(par.attr('data-multi') == 'true')
{
if($(this).hasClass('active'))
{
$(this).removeClass('active');
}
else
{
$(this).addClass('active');
}
}
else
{
$(this).parent().parent().find('input[checked]').removeAttr('checked')
$(this).parent().parent().find('.active').removeClass('active');
if($(this).hasClass('active'))
{
$(this).removeClass('active');
}
else
{
$(this).addClass('active');
}
$('.niceselect .value_wrapper').hide();
$('.select_style').removeClass('active')
}
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
checkBoxes.trigger('change')
})
$('body').on('click','.niceselect .value_wrapper .values label',function(e){e.preventDefault()})
$('body').on('change','.niceselect .values input',function(e){
var par = $(this).closest('.niceselect')
if(par.attr('data-multi') == 'true')
{
var number = par.find('input:checked').length;
par.find('p.top').html(number + ' Selected')
}
else
{
par.find('p.top').html($(this).attr('data-text'))
}
})
/*SEARCH OPTIONS IN SELECT BOX
----------------------------------------*/
var string = '';
$('body').on('keypress',function(e){
if($('.value_wrapper').is(':visible'))
{
var clearString;
$('.value_wrapper .highlight').removeClass('highlight')
clearInterval(clearString)
string = string+String.fromCharCode(e.which);
if(string.length == 1)
{
string = string.toUpperCase();
}
var thing = $('.value_wrapper:visible').find('label:contains('+string+')').first();
$(thing).parent().addClass('highlight')
if($('.value_wrapper:visible').find('.highlight').length > 0)
{
$('.value_wrapper:visible').stop().scrollTop($('.value_wrapper:visible').scrollTop() + $('.highlight').position().top)
}
clearString = setTimeout(function(){string = ''},500);
}
})
})
}
}( jQuery ));
I think that you want to do this:
/*CREATE GENERAL OPTION FIELDS*/
else
{
select.find('option').each(function(index,value){
var $this = $(this);
var val;
if($(this).val() == '')
{
val = $(this).html();
}
else
{
val = $(this).val();
}
var txt = $(this).html();
selected = '';
if(typeof( $(this).attr('selected') ) != 'undefined')
{
selected = 'checked';
select.siblings('.niceselect').find('p.top').html(txt)
}
select.siblings('.niceselect').children('.value_wrapper').append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" ><b>'+txt+'</b></label></div>')
})
}
select.remove()
select.attr('name','blobla')
Notice that I only have changed this line:
select.siblings('.niceselect').children('.value_wrapper').append('<div class="values"><input type="'+type+'" '+required+' '+selected+' style=" pointer-events: none;" name="'+name+multix+'" value="'+val+'" data-text="'+txt+'" id="'+index+name+index+'" /> <label class="nice_label" ><b>'+txt+'</b></label></div>')
Copy & paste this part of the code and test it.

How to submit form only one check box is selected using java script

on edit button click a want to submit form only if one check box checked,don't submit when 0 or more than 2 check box checked
my below code is not working
$("#editbtn_id").click(function () {
var cnt = 0;
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
});
if (ischecked) {
checkbox_value += $(this).val();
cnt = cnt + 1;
if (cnt == 0 || cnt > 1) {
alert(cnt);
alert("Please select one Test case");
return false;
}
}
return false;
});
HTML
<form action="/editSingletest/{{ testcase.id }}" method="post" onsubmit="return" >
<input type="checkbox"/>
</form>
You can achieve this by following code
$("#editbtn_id").click(function(){
var cnt=0;
var checkbox_checked_count = 0;
var form_submit = false;
$(":checkbox").each(function () {
if($(this).is(":checked")) {
checkbox_checked_count++
}
});
if(checkbox_checked_count == 1) {
form_submit = true;
}
else if(checkbox_checked_count > 1) {
alert("Please select one Test case");
}
alert(form_submit)
$("form").submit();
});
Check working example here in this fiddle
Your counter is in the wrong loop, should be something like this:
$("#editbtn_id").click(function(){
var cnt=0;
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked){
checkbox_value += $(this).val();
cnt=cnt + 1 ;
}
});
if(cnt==0 || cnt > 1){ ... }
});
try this
$("#editbtn_id").click(function (e) {
if($('form input[type="checkbox"]:checked').length == 1){
$('form').submit();
}
else{
e.preventDefault();
}
});
for 'form' use your form selector

CheckBoxList Items using JavaScript

I have a checkoxlist with a couple of items and an all option. The user can select all and I want this to check off all the options and if they uncheck all it will uncheck all options.
I have accomplished this with the following code.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
alert(chkBoxCount[0].checked);
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = chkBoxCount[0].checked //state;
}
return false;
}
</script>
cblAffiliation.Attributes.Add("onclick", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
The issue is that if I select any of the boxes it loops through and then sets them to whatever the all option is. I am having trouble figuring out the best way to get around this.
I want to avoid using a checkbox next to the checkboxlist, then I have to make that line up with the checkboxlist.
Simply check to see if the box clicked was the all option. If it was, then go ahead and change the rest of the boxes. If it isn't, then check all the options to see if they are all checked so you can update the 'All' checkbox.
EDIT
You might want to use onChange, instead of onClick, onClick will probably be called before the value on the given checkbox is changed.
Code not checked, please forgive syntax problems.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
var clicked = this;
alert(chkBoxCount[0].checked ? 'All is Checked' : 'All is not Checked');
alert(clicked == chkBoxCount[0] ? 'You Clicked All' : 'You Didn't click All');
var AllChecked = true; // Check the all box if all the options are now checked
for(var i = 1;i < chkBoxCount.length; i++)
{
if(clicked == chkBoxCount[0]) { // Was the 'All' checkbox clicked?
chkBoxCount[i].checked = chkBoxCount[0].checked; // Set if so
}
AllChecked &= chkBoxCount[i].checked; // AllChecked is anded with the current box
}
chkBoxCount[0].checked = AllChecked;
return false;
}
</script>
cblAffiliation.Attributes.Add("onchange", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
I think this code will help you.
<script type="text/javascript">
function check(checkbox)
{
var cbl = document.getElementById('<%=CheckBoxList2.ClientID %>').getElementsByTagName("input");
for(i = 0; i < cbl.length;i++) cbl[i].checked = checkbox.checked;
}
</script>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="check(this)" />
<asp:CheckBoxList ID="CheckBoxList2" runat="server">
<asp:ListItem>C1</asp:ListItem>
<asp:ListItem>C2</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="checkAll" runat="server" Text="Select/Unselect" onclick="CheckAll();" />
<asp:CheckBoxList ID="chkTest" runat="server" onclick="ClearAll();">
<asp:ListItem Text="Test 1" Value="0"></asp:ListItem>
<asp:ListItem Text="Test 2" Value="1"></asp:ListItem>
<asp:ListItem Text="Test 3" Value="2"></asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function CheckAll() {
var intIndex = 0;
var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
for (intIndex = 0; intIndex < rowCount; intIndex++)
{
if (document.getElementById('checkAll').checked == true)
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
document.getElementById("chkTest" + "_" + intIndex).checked = true;
}
}
else
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if (document.getElementById("chkTest" + "_" + intIndex).disabled != true)
document.getElementById("chkTest" + "_" + intIndex).checked = false;
}
}
}
}
function ClearAll(){
var intIndex = 0;
var flag = 0;
var rowCount=document.getElementById('chkTest').getElementsByTagName("input").length;
for (intIndex = 0; intIndex < rowCount; intIndex++)
{
if (document.getElementById("chkTest" + "_" + intIndex))
{
if(document.getElementById("chkTest" + "_" + intIndex).checked == true)
{
flag=1;
}
else
{
flag=0;
break;
}
}
}
if(flag==0)
document.getElementById('checkAll').checked = false;
else
document.getElementById('checkAll').checked = true;
}
</script>
function checkparent(id) {
var parentid = id;
var Control = document.getElementById(parentid).getElementsByTagName("input");
if (parentid.indexOf("List") != -1) {
parentid = parentid.replace("List", "");
}
if (eval(Control).length > 0) {
if (eval(Control)) {
for (var i = 0; i < Control.length; i++) {
checkParent = false;
if (Control[i].checked == true) {
checkChild = true;
}
else {
checkChild = false;
break;
}
}
}
}
if (checkParent == true && document.getElementById(parentid).checked == false) {
document.getElementById(parentid).checked = false;
checkParent = true;
}
else if (checkParent == true && document.getElementById(parentid).checked == true) {
document.getElementById(parentid).checked = true;
checkParent = true;
}
if (checkChild == true && checkParent == false) {
document.getElementById(parentid).checked = true;
checkParent = true;
}
else if (checkChild == false && checkParent == false) {
document.getElementById(parentid).checked = false;
checkParent = true;
}
}
function CheckDynamic(chkid) {
id = chkid.id;
var chk = $("#" + id + ":checked").length;
var child = id + "List";
if (chk != 0) {
$("[id*=" + child + "] input").attr("checked", "checked");
}
else {
$("[id*=" + child + "] input").removeAttr("checked");
}
checkparent(id);
}

Input box appears if dropdown "Other" is selected?

Here is my final code:
<script type="text/javascript">
jQuery(function() {
jQuery("#company").change(function() {
var val = jQuery(this).val();
if(val == 'other') {
jQuery('input[name="other"]').fadeIn('slow');
} else {
jQuery('input[name="other"]').fadeOut('slow')();
}
});
});
</script>
$(function() {
$("#dropdown").change(function() {
var val = $(this).val();
if(val == 'other') {
$('input[name="other"]').show();
} else {
$('input[name="other"]').hide();
}
}).change();
});
Updated. as box9 suggested, since you want the function to trigger on page load.

Categories

Resources