<script src="https://js.arcgis.com/4.25/"></script>
<script src="https://cdn.jsdelivr.net/gh/harvesthq/chosen#gh-pages/docsupport/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/harvesthq/chosen#gh-pages/chosen.jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/harvesthq/chosen#gh-pages/chosen.min.css" rel="stylesheet">
<script>
$(document).ready(function() {
$(".chosen-select").chosen({
no_results_text: "Oops, nothing found!"
})
});
</script>
<script>
var dict1 = {'Canada': ['', 'Toronto'],'USA': ['', 'Hawaii']};
var dict2= {'Toronto': ['','A', 'B'],Hawaii': ['C', 'D']};
var dict3 = {'A': ['Item1', 'Item2'],
'B': ['Item3', 'Item4'],
'C': ['Item5', 'Item6'],
'D': ['Item7', 'Item8']
};
var regionOption = document.querySelector("#municipality");
var districtOption = document.querySelector("#districtName");
var provOption = document.querySelector("#region");
var neighOption = document.querySelector("#selectNeigh");
createOption(provOption, Object.keys(regions));
provOption.addEventListener('change', function() {
createOption(regionOption, dict1[provOption.value]);
});
regionOption.addEventListener('change', function() {
createOption(districtOption, dict2[regionOption.value]);
});
districtOption.addEventListener('change', function() {
createOption(neighOption, dict3[districtOption.value]);
});
function createOption(dropDown, options) {
dropDown.innerHTML = '';
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
};
</script>
<body>
<select id="region" style="width: 125px;"></select>
<select id="municipality" style="width: 125px;"></select>
<select id="districtName" style="width: 125px;"></select>
<form action="http://httpbin.org/post" method="post">
<select data-placeholder='Select Neighbourhoods' id="selectNeigh" multiple class='chosen-select'style="width: 125px;"></select>
</form>
</body>
So my current code works fine if I use the regular html multiple select. However, when I implement the following code: HTML: Select multiple as dropdown. The options are no longer being populated for select eight. Can someone please help me out.
From https://harvesthq.github.io/chosen/
If you need to update the options in your select field and want Chosen
to pick up the changes, you'll need to trigger the "chosen:updated"
event on the field. Chosen will re-build itself based on the updated
content.
$("#form_field").trigger("chosen:updated");
So you have trigger the update event in your createOption function.
function createOption(dropDown, options) {
dropDown.innerHTML = '';
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
$(".chosen-select").trigger("chosen:updated");
};
Related
I need to create an enhanced transferbox, using HTML, JavaScript and JQuery.
I have a set of options a user can select from and associate with an attribute. The selection and deselection must be accomplished with two SELECT HTML elements (i.e., a transferbox). For example, these options can be a list of skill names.
When the 'add' button is clicked, the option(s) selected in the first SELECT element, along with an attribute (e.g. number of years from a text box) must be transferred from the source SELECT element to selected/destination SELECT element. The attribute must be displayed along with the item text in this second SELECT element (for example, the item displays the skill and the number of years).
When the 'remove' button is clicked, the selected option(s) in the second SELECT element must be moved back to the first SELECT element (in the original format .. without the attribute).
JSON should be the data format for initial selection setup and saving latest selections.
I want an initial set of selections and attributes to be set via JSON in an a hidden input field. I want the final set of selections to be saved to JSON in the same hidden input field.
Example HTML:
<input type="hidden" id="SelectionsId" value='[{ "id": "2", "attribute":"15"},{ "id": "4", "attribute":"3" }]' />
<!--<input type="hidden" id="SelectionsId" value='[]' />-->
<div>
<select class="MultiSelect" multiple="multiple" id="SelectFromId">
<option value="1">.NET</option>
<option value="2">C#</option>
<option value="3">SQL Server</option>
<option value="4">jQuery</option>
<option value="5">Oracle</option>
<option value="6">WPF</option>
</select>
<div style="float:left; margin-top:3%; padding:8px;">
<div>
<span>Years:</span>
<input id="YearsId" type="number" value="1" style="width:36px;" />
<button title="Add selected" id="includeBtnId">⇾</button>
</div>
<div style="text-align:center;margin-top:16%;">
<button title="Remove selected" id="removeBtnId">⇽</button>
</div>
</div>
<select class="MultiSelect" multiple="multiple" id="SelectToId"></select>
</div>
<div style="clear:both;"></div>
<div style="margin-top:40px;margin-left:200px;">
<button onclick="SaveFinalSelections();">Save</button>
</div>
Example CSS:
<style>
.MultiSelect {
width: 200px;
height: 200px;
float: left;
}
</style>
Visual of requirement:
Here's a solution to the challenge. The variables being setup at the start make this solution easy to configure and maintain.
When the page gets displayed, the SetupInitialSelections method looks at the JSON data in the hidden input field and populates the selected items.
When the 'Save' button clicked, the current selections are converted to JSON and placed back in the hidden input field.
Invisible character \u200C is introduced to delimit the item text and the attribute during display. This comes in to use if the item has to be removed and the original item text has to be determined so it can be placed back in the source SELECT element.
The selectNewItem variable can be set to true if you would like the newly added item to be selected soon after adding it to the SELECT element via the 'add' or 'remove' operations.
This solution supports multiple item selections. So multiple items can be added at once ... and similarly multiple items can be removed at once.
<script src="jquery-1.12.4.js"></script>
<script>
var savedSelectionsId = 'SelectionsId';
var fromElementId = 'SelectFromId';
var toElementId = 'SelectToId';
var includeButtonId = 'includeBtnId';
var removeButtonId = 'removeBtnId';
var extraElementId = 'YearsId';
var extraPrefix = " (";
var extraSuffix = " years)";
var noItemsToIncludeMessage = 'Select item(s) to include.';
var noItemsToRemoveMessage = 'Select item(s) to remove.';
var selectNewItem = false;
var hiddenSeparator = '\u200C'; // invisible seperator character
$(document).ready(function () {
SetupInitialSelections();
//when button clicked, include selected item(s)
$("#" + includeButtonId).click(function (e) {
var selectedOpts = $('#' + fromElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToIncludeMessage);
e.preventDefault();
return;
}
var attribute = $("#" + extraElementId).val();
selectedOpts.each(function () {
var newItem = $('<option>', { value: $(this).val(), text: $(this).text() + hiddenSeparator + extraPrefix + attribute + extraSuffix });
$('#' + toElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
//when button clicked, remove selected item(s)
$("#" + removeButtonId).click(function (e) {
var selectedOpts = $('#' + toElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToRemoveMessage);
e.preventDefault();
return;
}
selectedOpts.each(function () {
var textComponents = $(this).text().split(hiddenSeparator);
var textOnly = textComponents[0];
var newItem = $('<option>', { value: $(this).val(), text: textOnly });
$('#' + fromElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
});
// Setup/load initial selections
function SetupInitialSelections() {
var data = jQuery.parseJSON($("#" + savedSelectionsId).val());
$.each(data, function (id, item) {
var sourceItem = $("#" + fromElementId + " option[value='" + item.id + "']");
var newText = sourceItem.text() + hiddenSeparator + extraPrefix + item.attribute + extraSuffix;
$("#" + toElementId).append($("<option>", { value: sourceItem.val(), text: newText }));
sourceItem.remove();
});
}
// Save final selections
function SaveFinalSelections() {
var selectedItems = $("#" + toElementId + " option");
var values = $.map(selectedItems, function (option) {
var textComponents = option.text.split(hiddenSeparator);
var attribute = textComponents[1].substring(extraPrefix.length);
var attribute = attribute.substring(0, attribute.length - extraSuffix.length);
return '{"id":"' + option.value + '","attribute":"' + attribute + '"}';
});
$("#" + savedSelectionsId).val("[" + values + "]");
}
</script>
I have a table that I get from my MySQL base using ajax. The answer from ajax makes the table in a DIV wrapper.
Now I need to edit this table and if it is needed to save it, but I've got several problems.
My plan was to make a $('td').click() append an input and after pressing enter or clicking anywhere the input should be hidden and the clear TD with new value should appear. After that I presss the UPDATE button and save my row to DB.
But my JavaScript skills are not so good and I failed even with 100 of examples.
Here is my code:
$('#load').click(function() {
//the load button - gets the table from DB
//here I get some data from the website filter.
var data = new webmaster(pid, name, email, skype, web, current_offer, lookingfor_offer, anwsered, comment);
data = JSON.stringify(data);
$('#aw-wrapper').empty();
$.ajax({
type: "POST",
data: {
"data": data
},
url: "inc/load-web.php",
success: function(anwser) {
$('#aw-wrapper').html(anwser);
TableEdit();
}
});
});
function TableEdit() {
if (i) {
$('td').click(function() {
this.onclick = null;
var td_value = $(this).html();
var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
$(this).empty().append(input_field);
$('input').focus();
i = 0;
});
}
}
But it doesnot work at all. I got many clicks on td instead of one. Maybe I am doing it wrong and it can be realized easier?
I dont see where i is defined. I changed your function to look like this:
function TableEdit() {
var i = 1;
$('td').click(function() {
if (i) {
this.onclick = null;
var td_value = $(this).html();
var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
$(this).empty().append(input_field);
$('input').focus();
i = 0;
}
});
}
if I understand what you want i believe it gives the desired result, however, this is how i would implement this
function TableEdit() {
$('td').click(function() {
var td_value = $(this).html();
var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
$(this).empty().append(input_field);
$('input').focus();
$('td').off('click');
$(this).find('input').blur(function(){
var new_text = $(this).val();
$(this).parent().html(new_text);
TableEdit();
})
});
}
updated fiddle https://jsfiddle.net/vf2L78p8/2/
I have used a Bootstrap dialog box to get a file input, where the user first selects the type and then selects the file - I want to limit the files by extension with regard to the type selected.
Bootstrap dialog is built by a string and I was thinking of adding an onchange event to the selector as in the following, which I hoped would update the extension in accept in file input - but it gives an error setType is not defined.
How can I correctly dynamically capture the selected type and set it in the accept in the input where the HTML is built from string?
JSFiddle
var HTMLmessage = 'Type: <select onchange="setType(this)"> ..Option list </select> <br> <input type="file" accept=' + getType() + '>';
You can simply use jQuery for this. and use on(change) event of jQuery.
Here is the FIDDLE.
Piece of code
$(document).on("change", '#load-file-type', function(event) {
getType = $(this).find('option:selected').attr('data-ext');
$('#load-file').attr('accept',getType); // simply using this you can set it in the `accept` in file input.
});
Which allow you to trigger event on change.
you need event delegation https://jsfiddle.net/0c3d0885/1/ . As you are modifing/adding element after DOMload
document.getElementById('load-file-type').onchange = function setType(op) {
console.log(op);
getType = op.dataset.dataExt;
}
You could use event bubbling to be able to capture elements that are created at runtime. Similar to jQuerys event delegation.
Here is what you could do.
var optionList = [{
name: "XML",
id: "xmlVAL",
extension: ".xml"
}, {
name: "JSON",
id: "jsonVAL",
extension: ".json"
}, {
name: "CSV",
id: "csvVAL",
extension: ".csv"
}];
var typeOptions = (function(arr) {
var str = "";
arr.map(function(type) {
var op = "<option value=" + type.id + " data-ext=" + type.extension + " >" + type.name + "</option>";
str += op;
});
return str;
})(optionList);
var getType = ".xml";
function setType(op) {
// console.log(op);
getType = op.dataset.dataExt;
}
var message = ' Type: <select id="load-file-type" >' + typeOptions + ' </select> <br> File: <input id="load-file" type="file" style="display:inline" accept=' + getType + ' >'
document.getElementById("result").addEventListener("change", function(event) {
var target = event.target;
if (target.tagName.toLowerCase() !== "select") {
return;
};
console.log(target.options[target.selectedIndex].dataset.ext);
});
document.getElementById("result").innerHTML = message;
<div id="result">
</div>
i want add text-boxes on each click that work well but i need add id for each text-boxes which is added dynamical. i am struggling to give id for it below i give the code used for adding textbox on click
$(function() {
$('.plusicon').on('click', function() {
var textBox = '<input type="text" class="textbox"/>';
var a = $(this).attr("id");
$('#' + a + "box").append(textBox);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />//for clickbutton//
<div id="plusicondivbox" class="insidediv " style="margin-top:-53px;"></div>//div for adding txtbox//
Have a global-variable and increment it after every click-event
$(function() {
var count = 0;
$('.plusicon').on('click', function() {
var textBox = '<input type="text" class="textbox"/>';
var a = $(this).attr("id");
$('#' + a + "box").append(textBox);
$('#' + a + "box input:last").attr('id', 'id_' + count);
++count;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<br/>
<div id="plusicondivbox" class="insidediv"></div>
Or assign inline attribute by concatenation:
$(function() {
var count = 0;
$('.plusicon').on('click', function() {
var textBox = '<input type="text" id="id_' + count + '" class="textbox"/>';
var a = $(this).attr("id");
$('#' + a + "box").append(textBox);
++count;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<br/>
<div id="plusicondivbox" class="insidediv"></div>
Use instead of $(this) $(textbox)
$(function () {
$('.plusicon').on('click', function () {
var textBox = '<input type="text" class="textbox"/>';
var a = $(textBox).attr("id","your_id");
$('#'+a+"box").append(textBox);
});
Please have a look at below code. We can define global counter which will get incremented each time you press plus button so that you will get unique number each time. that number we can use to define unique textbox id as follows:
var textBoxCounter = 1;
$(function() {
$('.plusicon').on('click', function() {
var textBox = '<input type="text" class="textbox"/>';
textBox = $(textBox);
textBox.attr("id", "myTextBox_" + textBoxCounter);
textBoxCounter++;
var a = $(this).attr("id");
$('#' + a + "box").append(textBox);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<div id="plusicondivbox" class="insidediv " style="margin-top:53px;"></div>
This code will work for you ,use global variable which will give dynamicid for your textboxes ie(different id for dynamic textboxes):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</script>
<script>
var idCount=0;
$(function() {
$('p').on('click', function() {
var textBox = '<input type="text" class="textbox"/>';
var a = $('<input>').attr("id","textBox"+idCount);
$(textBoxDiv).append(a);
idCount++;
});
});
</script>
</head>
<body>
<p>Click !</p>
<div id="textBoxDiv" style="width:50%;height:50%">
</div>
</body>
</html>
I know this answer has already been accepted, but I dislike the option of using a global variable just to increment the count for the dynamically added id - when there is a cleaner way of doing it in the function using the length of the .textbox elements. Note that this will give a zero-indexed number for the id that is incremented each time the image is clicked, because each time a textbox is appended - the length of the .textbox class increases by 1. I have put a console.log in there to demonstrate the increasing count:
$('.plusicon').on('click', function() {
var textBox = '<input type="text" class="textbox"/>';
var textboxLength = $('.textbox').length;
$('#plusicondivbox').append(textBox);
$('.textbox:last').attr('id', 'id_' + textboxLength);
console.log('id_' + textboxLength);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<div id="plusicondivbox" class="insidediv " style="margin-top:53px;"></div>
I have a problem with get value form select > option.
I make option that:
$.each(response, function(i, element)
{
var nazwaKategori = element.name;
var idKategori = element.id;
$("#kategoria").append("<option>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
});
In body:
<form role="form">
<div class="form-group">
<label align="center" for="text">Lista dostępnych kategorii.</label>
<select class="form-control" id="kategoria">
<div id="kategoria">
</div>
</select>
<div id="wypisz"><div>
</div>
</form>
And i get this option:
<script>
$( "#kategoria" ).change(function () {
var str = "";
$( "#kategoria option:selected" ).each(function() {
str += $(this.KategoriaID).val() + " ";
});
$( "#wypisz" ).text( str );
})
.change();
</script>
How i can get only idKategori ? I musc find pattern in get text?
Thanks
Well apart of having a wrong html structure with a div inside a select, when you are creating your dropdown, you could use something like this:
$("#kategoria").append("<option value='"+idKategori+"'>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
So every option will have a value and then in the change event you could use this:
$( "#kategoria" ).on("change", function () {
var optionselected = $(this).find(":selected").val();
//HEre you will have you value of the option selected in a variable
console.log(optionselected);
});
I don't know if thats what you wanted, and I don't know if your dropdown creation is working, but your questions is to get value from select option with jquery. Hope this helps