How to select an option text matching those of an array value - javascript

I have an array with three elements, Im looping through that array to see the length of it so that it triggers a button click three times to dynamic add input select box. Each array value will go on each added select box and find if it match any option text if it does it have to select it. Below is my code not sure where I'm going wrong
var myArryValues = [
"Hello World",
"Javascript",
"Jquery"
]
for (var i = 0; i < myArryValues.length; i++) {
var bookIndex = 0;
$('#bookForm').on('click', '.mynewButton', function() {
$('.myDropdown').each(function(index) {
console.log("operatorString", operatorString);
var operatorCounter = 0;
var optionCounter = 0;
$(this).find('option').filter(function() {
if ($(this)[optionCounter] == myArryValues[operatorCounter]) {
$(this)[optionCounter].attr('selected', "selected");
operatorCounter++;
} else {
optionCounter++;
}
});
});
console.log("mynewButton");
bookIndex++;
var bookForm = $('#bookForm');
var $template = $('#bookTemplate'),
$clone = $template
.clone()
.addClass('myDropdown-row')
.removeClass('hide')
.attr('data-book-index', bookIndex)
.attr('id', '');
bookForm.append($clone);
// Update the name attributes
$clone
.find('[name="myDropdown"]').attr('name', 'myDropdown[' + bookIndex + '].myDropdown').end()
})
// Remove button click handler
.on('click', '.removeButton', function() {
$(this).parents('.form-group').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="row" id="bookForm" class="form-horizontal">
<div class="form-group">
<div class="col-md-2 button-div">
<button type="button" class="mynewButton rule-button">Add New
</button>
</div>
</div>
<!-- The template for adding new field -->
<div class="form-group hide" id="bookTemplate">
<div class="row field-row">
<div class="col-md-2">
<select class="myDropdown" name="myDropdown">
<option value="Hello World">Hello World</option>
<option value="Javascript">Javascript</option>
<option value="Jquery">Jquery</option>
</select>
</div>
</div>
</div>
</div>

Try This on your click function
var data = ['bar','baz'];
for (var i = 0; i < data.length; i++) {
var s = $('<select id="'+i+'"/>');
for (var j = 0; j < data.length; j++) {
if (i==j) {
$('<option />', {value: data[j], text: data[j],selected:'selected'}).appendTo(s);
}else{
$('<option />', {value: data[j], text: data[j]}).appendTo(s);
}
}
s.appendTo('body');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Related

select2 not working with hidden parent div (dynamicaly created select elements)

I'm dynamicaly creating divs with a select2 select element. The problem is, it somehow loosk like it doesn't find the object when initializing the select2.
has anyone run into that problem before?
this is my code so far:
HTML:
<button id="addNewDocument" class="col-2 btn btn-primary add-doc-button">Neues Dokument</button>
<div style="display: none;">
<div id="docDescription" class='col-md-4 form-group documentDescription'>
<label class='control-label input-label'>Dokumenttyp</label>
<select class='form-control documentDescriptionSelect required' name='Chose Documenttype'>
<option value=""></option>
#foreach (var item in Model.DocumentTypes)
{
<option class="row" value='#item.Documentcode'>
<div>#Html.DisplayFor(modelItem => item.Documentcode)</div>
<div> - </div>
<div>#Html.DisplayFor(modelItem => item.Documentname)</div>
</option>
}
</select>
</div>
</div>
JS:
$("#addNewDocument").click(function () {
var uid = Math.floor(Math.random() * 26) + Date.now()
var selectID = uid + 1;
var newDocumentBox = $("<li class='row documentContainer justify-content-between' id='" + uid + "'></li>").prependTo("#newDocuments");
var newDocumentDescription = $("#docDescription").clone(true);
$("#docDescription").children().eq(1).attr("id", selectID);
newDocumentDescription.appendTo(newDocumentBox);
var newDroppableBox = $("<div class='documents col-md-7 droppableBox' ></div>").appendTo(newDocumentBox);
var newDeleteButton = $("<div class='close-container deleteButton' onclick='deleteDocument(" + uid + ")'><div class='leftright'></div><div class='rightleft'></div></div>").appendTo(newDroppableBox);
$(selectID).select2({
placeholder: "Bitte wählen Sie einen Dokumenttyp"
})
});

Record data to proper html children elements when cloning

I have a form in Google sheets where I send dynamic data from the sheet.
I loop sheet data and create same number of blocks in a form as number of my headers.
I have a first block of elements written in html.
The rest of blocks I clone from the first one, clone its IDs and send my sheet titles to elements of the form.
First title I write (with the last title from an array) to the only block existing before looping.
Then I clone that block giving a clone new titles and trying to insert clones before the first block ([0]) but it gets wrong and overwrites my first hardcoded title.
It appends the blocks in random number, so I can't get my titles in the right sequence like "1,2,3".
It's always like "2,1,1" or "1,3,2" etc.
I've tried different variations of appending the cloned elements (like motherDiv.appendChild(clonedRow) and motherDiv.insertBefore(clonedRow, motherDiv.children[0]), but cannot get it to work properly.
Please point to what's wrong here.
Here's the code and the screen:
//my google app backend function with data
var numbers = [1, 2, 3]
var stats = ["Валовый доход", "Кол-во клиентов", "Кол-во размещенной рекламы"]
var stats = {
statNumbers: numbers,
statStats: stats
}
//select initialization
document.addEventListener('DOMContentLoaded', function() {
var getstats = getStats();
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
//getting stats object
function getStats() {
google.script.run.withSuccessHandler(processStats).statsObj();
google.script.run.withFailureHandler(showError).statsObj()
return;
}
//creating dynamic stats fields in the form
function processStats(stats) {
//name first statistic with the last number
var firstStat = document.getElementById("statName").innerHTML = stats.statNumbers[stats.statStats.length - 1] + ". " + stats.statStats[stats.statStats.length - 1]
//mother div
var motherDiv = document.getElementById("motherDiv")
//sample row to copy
var statRow = document.getElementById("statsample");
//loop stat names
for (var i = 0; i < stats.statStats.length - 1; i++) {
var statName = stats.statStats[i]
var statNumber = stats.statNumbers[i]
//cloning the original row
var clonedRow = statRow.cloneNode(true)
//setting unique ID to whole row
var rowId = clonedRow.id = "statsample" + i
//setting unique ID to stat div
var clonedStatID = motherDiv.getElementsByClassName("statClass")[0].id = "statName" + statNumber
//stat titles (except first one)
var statHtml = document.getElementById(clonedStatID).innerHTML = statNumber + ". " + statName;
var err = document.getElementById("err").innerHTML = motherDiv.children.length
//appending it to the mother div
//motherDiv.appendChild(clonedRow);
motherDiv.insertBefore(clonedRow, motherDiv.children[0]);
}
return;
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div id="motherDiv">
<!-- mother div -->
<div class="row" id="statsample">
<div class=" input-field col s3 #fffde7 yellow lighten-5">
<h6 id="statName" class="statClass"></h6>
</div>
<div class="input-field col s3">
<select class="icons browser-default" id="weeksSel4">
<option value="" disabled selected>Неделя</option>
</select>
</div>
<div class="input-field col s2">
<input id="numbers" type="text" class="validate">
<label for="numbers">Значение</label>
</div>
<div class="input-field col s1.5">
<select class="icons browser-default" id="measure">
<option value="" disabled selected>Ед. изм:</option>
<option value="">шт.</option>
<option value="">%</option>
<option value="">$</option>
<option value="">руб.</option>
<option value="">грн.</option>
</select>
</div>
<div class="input-field col s2.5">
<a class="waves-effect waves-light btn-small #039be5 light-blue darken-1" style="float: right;" id="btn1row"><i class="material-icons right">send</i>Ввести</a>
</div>
</div>
<!-- row end -->
</div>
<!-- mother div end-->
<div id="err"> </div>
I'd recommend populating the 'master' div with the first element of the array and for the clones start iterating over the array from index 1.
We need to make some fundamental changes to your processStats(stats) function.
First populate the master:
var firstStat = document.getElementById("statName").innerHTML = stats.statNumbers[0] + ". " + stats.statStats[0];
the following two lines are untouched
var motherDiv = document.getElementById("motherDiv")
var statRow = document.getElementById("statsample");
Change the for loop to start from 1
for (var i = 1; i < stats.statStats.length; i++) {
}
Now the for-loop itself needs some changes.
These three lines are okay
var statName = stats.statStats[i];
var statNumber = stats.statNumbers[i];
var clonedRow = statRow.cloneNode(true);
What I don't understand is the following
var clonedStatID = motherDiv.getElementsByClassName("statClass")[0].id = "statName" + statNumber
I know you want to give the freshly cloned divs child statClass a unique id with a sequential number but with every iteration of the for-loop this would give the first element in the list the id. Above you already have a variable which holds a reference to the cloned div clonedRow you can also use to access it's children.
So get rid of the line and use this:
clonedRow.getElementsByTagName("h6")[0].innerHTML = statNumber + ". " + statName;
Now just append the div to the parent
motherDiv.appendChild(clonedRow);
Here's a working example - just click 'Run code snippet' to see it in action:
//my google app backend function with data
var numbers = [1, 2, 3]
var stats = ["Валовый доход", "Кол-во клиентов", "Кол-во размещенной рекламы"]
var stats = {
statNumbers: numbers,
statStats: stats
}
function processStats(stats) {
//name first statistic with the last number
var firstStat = document.getElementById("statName").innerHTML = stats.statNumbers[0] + ". " + stats.statStats[0];
//mother div
var motherDiv = document.getElementById("motherDiv")
//sample row to copy
var statRow = document.getElementById("statsample");
//loop stat names
for (var i = 1; i < stats.statStats.length; i++) {
var statName = stats.statStats[i];
var statNumber = stats.statNumbers[i];
var clonedRow = statRow.cloneNode(true);
var rowId = clonedRow.id = "statsample" + i;
clonedRow.getElementsByTagName("h6")[0].innerHTML = statNumber + ". " + statName;
var err = document.getElementById("err").innerHTML = motherDiv.children.length
motherDiv.appendChild(clonedRow);
}
return;
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
processStats(stats);
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div id="motherDiv">
<!-- mother div -->
<div class="row" id="statsample">
<div class=" input-field col s3 #fffde7 yellow lighten-5">
<h6 id="statName" class="statClass"></h6>
</div>
<div class="input-field col s3">
<select class="icons browser-default" id="weeksSel4">
<option value="" disabled selected>Неделя</option>
</select>
</div>
<div class="input-field col s2">
<input id="numbers" type="text" class="validate">
<label for="numbers">Значение</label>
</div>
<div class="input-field col s1.5">
<select class="icons browser-default" id="measure">
<option value="" disabled selected>Ед. изм:</option>
<option value="">шт.</option>
<option value="">%</option>
<option value="">$</option>
<option value="">руб.</option>
<option value="">грн.</option>
</select>
</div>
<div class="input-field col s2.5">
<a class="waves-effect waves-light btn-small #039be5 light-blue darken-1" style="float: right;" id="btn1row"><i class="material-icons right">send</i>Ввести</a>
</div>
</div>
<!-- row end -->
</div>
<!-- mother div end-->
<div id="err"> </div>

Height of dropdown box in multiselect option

Im using multiselect dropdown for my select control. Im adding options to select control in Javascript. Reading data from database through PHP and passing to javascript file. But the height of the options dropdown is small like i can only see 'Select All' check box with out any scrolling. But if i add the options in HTML itself, then the dropdown looks fine. What im missing here?
<script src="<?=BASE_URL?>dropdown/multiple-select.js"></script>
<link href="<?=BASE_URL?>dropdown/multiple-select.css" rel="stylesheet">
<div class="modal" id="SendmailModel" tabindex="-1" role="dialog" aria-labelledby="messageModelLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><li class="fa fa-times"/></button>
<h3 style="font-size: 17px;">Send Mail </h3>
</div>
<div class="modal-body">
<form id="mailcomposeForm" id="_id_">
<div class="control-group">
<label class="control-label">Event Details</label>
<div class="controls">
<table class="table table-condensed table-bordered table-striped" id="event_days_table" style="display: none;width:544px;font-size:14px;">
<tbody id="event_days_table_body">
</tbody>
</table>
</div>
</div>
<div class="control-group">
<label class="control-label" for="leave_status">Select Recipient(s)</label>
<select id="emplist" name="employee_name" value="" multiple="multiple">
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" onclick="modJs.SendingMail();">Send</button>
<button class="btn" onclick="modJs.closemaildialog();">Not Now</button>
</div>
</div>
</div>
</div>
script type="text/javascript">
$(function() {
$('#emplist').change(function() {
}).multipleSelect({
width: '100%',
height:'100%'
});
});
</script>
In my Javascript file..
Conferencelisting.method('MailSuccessCallback', function(callBackData) {
var row = '<tr><th>From</th><td>_from_</td></tr><tr><th>To</th><td>_to_</td></tr><tr><th>Type</th><td>_type_</td></tr><tr><th>Created By</th><td>_created_</td><tr><th>Details</th><td>_details_</td></tr>';
var eventdetails = callBackData[0];
var html = "";
var trow = "";
for(var i=0;i<eventdetails.length;i++){
trow = row;
trow = trow.replace(/_from_/g,Date.parse(eventdetails[i].From).toString('d MMM yyyy <b>h:mm tt</b>'));
trow = trow.replace(/_to_/g,Date.parse(eventdetails[i].To).toString('d MMM yyyy <b>h:mm tt</b>'));
trow = trow.replace(/_type_/g,eventdetails[i].type);
trow = trow.replace(/_created_/g,eventdetails[i].employee);
trow = trow.replace(/_details_/g,eventdetails[i].reason);
html += trow;
}
$('#event_days_table_body').html(html);
$('#event_days_table').show();
//Adding employees name in selection box.
var emplist = callBackData[1];
var options = '';
for (var i = 0; i < emplist.length; i++) {
options += '<option value="' + emplist[i].id + '">' + emplist[i].name+ '</option>';
}
$("#emplist").html(options);
$('#SendmailModel').modal('show');
});
If i add options in HTML file like this..i can get exact dropdown with scrolls..
<select id="emplist" name="employee_name" value="" multiple="multiple">
<option value="ALEX">ALEX</option>
<option value="BOB">BOB</option>
<option value="DE">DE</option>
</select>
I solved myself. I think the height is not the problem , the data are not getting added. SO i changed options adding code in javascript file. Now it works.
var emplist = callBackData[1];
var options = '';
for (var i = 0; i < emplist.length; i++) {
$('#emplist').append( '<option value="' + emplist[i].id + '">' + emplist[i].name+ '</option>' );
}
$('#emplist').multipleSelect( 'refresh' );

JavaScript remove element from multiple select boxes

I have a form where I have a select box and a drop down menu with two buttons and a text field. Enter an item into the text field and it gets added to BOTH the select box above AND the drop down menu. I can figure out how to remove the selected item from the select box but how do I ALSO remove it from the drop down menu??
Working JS FIDDLE EXAMPLE
NOTE: On the actual form these will be on different tabs so you won't be able to see them at the same time, the list just needs to populate from one area to the other.
CSS
#sbox {
overflow: hidden;
width: 200px;
}
HTML
<select id="sbox" name="selectbox" size="5"></select>
<BR>
<button type="button" class="btn btn-default" onclick="DeleteProbs();">Delete Selected Problem</button>
</td>
</tr>
<tr>
<td colspan="2" valign="top"><p>To add a problem to the list, type it in the New Problem text field and then click "Add to List". To remove a problem, click it in the list, then click, "Delete Selected Problem"<P>
<strong>New Problem</strong><P>
<input type="text" id="ProbAreaFrom">
<P>
<button type="button" class="btn btn-default" id="ProbListBtn" onclick="ListProbs();">Add to List</button>
</p>
Problem being detailed:<BR>
<select name="select" id="dbox">
</select>
JAVASCRIPT
function ListProbs() {
var x = document.getElementById("sbox");
var txt1 = document.getElementById("ProbAreaFrom").value;
var option = document.createElement("option");
option.text = txt1
x.add(option);
ListProbs2();
}
function ListProbs2() {
var y = document.getElementById("dbox");
var txt1 = document.getElementById("ProbAreaFrom").value;
var option = document.createElement("option");
option.text = txt1
y.add(option);
ProbAreaFrom.value="";
}
function DeleteProbs() {
var x = document.getElementById("sbox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected) {
x.options[i].remove();
}
}
}
function DeleteProbs() {
var x = document.getElementById("sbox");
var y = document.getElementById("dbox");
var val;
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected) {
val = x.options[i].value;
x.options[i].remove();
}
}
for (var i = 0; i < y.options.length; i++) {
if (y.options[i].value == val) {
y.options[i].remove();
}
}
}
working fiddle. Added a button to remove selected item from select element. The function's name is
DeleteProbs2
http://jsfiddle.net/4uBYf/2/
function ListProbs() {
var x = document.getElementById("sbox");
var txt1 = document.getElementById("ProbAreaFrom").value;
var option = document.createElement("option");
option.text = txt1
x.add(option);
ListProbs2();
}
function ListProbs2() {
var y = document.getElementById("dbox");
var txt1 = document.getElementById("ProbAreaFrom").value;
var option = document.createElement("option");
option.text = txt1
y.add(option);
ProbAreaFrom.value="";
}
function DeleteProbs() {
var x = document.getElementById("sbox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected) {
x.options[i].remove();
}
}
}
function DeleteProbs2() {
var index = $('#dbox').get(0).selectedIndex;
$('#dbox option:eq(' + index + ')').remove();
}
html
<div class="table-responsive">
<table class="table table-bordered">
<tbody>
<tr>
<td colspan="2" valign="top">
Problem List:<BR />
<select id="sbox" name="selectbox" size="5"></select>
<BR>
<button type="button" class="btn btn-default" onclick="DeleteProbs();">Delete Selected Problem</button>
</td>
</tr>
<tr>
<td colspan="2" valign="top"><p>To add a problem to the list, type it in the New Problem text field and then click "Add to List". To remove a problem, click it in the list, then click, "Delete Selected Problem"<P>
<strong>New Problem</strong><P>
<input type="text" id="ProbAreaFrom">
<P>
<button type="button" class="btn btn-default" id="ProbListBtn" onclick="ListProbs();">Add to List</button>
</p>
Problem being detailed:<BR>
<select name="select" id="dbox">
</select>
<button type="button" class="btn btn-default" id="test" onclick="DeleteProbs2();">remove from select</button>
</td>
</tr>
</tbody>
</table>
</div>
update for your request (first button removes from both elements)
http://jsfiddle.net/4uBYf/5/
function DeleteProbs() {
var x = document.getElementById("sbox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected) {
var text=$( "#dbox option:selected" ).text();
$('#dbox option').filter(function () { return $(this).html() == text; }).remove();
x.options[i].remove();
}
}
}

Multiple Chained SELECT Tag JavaScript and jQuery

Good Day! :)
I created a chained select using php and jQuery like on this page http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/ and I created a javascript to add and delete select tags I get it somewhere on the internet
but what happening is when I choose a category on the first line everything on the subcategory will be enabled and also on the product description. Just like this http://i.stack.imgur.com/H9nfb.jpg
this is my code:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select#type").attr("disabled", "disabled");
$("select#category").change(function() {
$("select#type").attr("disabled", "disabled");
$("select#type").html("<option>wait...</option>");
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {
id: id
}, function(data) {
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("select#desc").attr("disabled", "disabled");
$("select#type").change(function() {
$("select#desc").attr("disabled", "disabled");
$("select#desc").html("<option>wait...</option>");
var id = $("select#type option:selected").attr('value');
$.post("select_desc.php", {
id: id
}, function(data) {
$("select#desc").removeAttr("disabled");
$("select#desc").html(data);
});
});
$("form#select_form").submit(function() {
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
var descr = $("select#desc option:selected").attr('value');
if (cat > 0 && type > 0 && descr > 0) {
var result = $("select#desc option:selected").html();
$("#result").html('your choice: ' + result);
} else {
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
<input type="button" value="Add" onclick="addRow('tableID')" />
<input type="button" value="Delete" onclick="deleteRow('tableID')" />
<table id="tableID">
<tr>
<td></td>
<td>Category</td>
<td>SubCategory</td>
<td>Product Description</td>
</tr>
<tr>
<td>
<input type="checkbox" name="chkbox[]" />
</td>
<td>
<select id="category" name="category[]">
<?php echo $opt->ShowCategory(); ?></select>
</td>
<td>
<select id="type" name="type[]">
<option value="0">choose...</option>
</select>
</td>
<td>
<select id="desc" name="desc[]">
<option value="0">choose...</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="confirm" />
</form>
<div id="result" name="result[]"></div>
</body>
</html>
Hope anyone could help me. :)
<select type='text' class='chosen-select'>
<option value='initial'>Select One...</option>
</select>
<select 'type='text' class='chosen-select' >
<option value='1' class='initial'>-----</option>
</select>
Use something like this. If 'Select One' is selected by user, it will display '----' in the next button. Set classes accordingly to make it work for you.

Categories

Resources