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>
Related
I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?
<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();
SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions
Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});
I have a form where a user can choose their Occupation. The list of occupations are in a seperate .js file like so:
var occupationSelect = "<select id='occupationSelect' onchange='selectChange()' ><option value=''></option><option value='v10173' >AA Patrolman</option><option value='v10174' >Abattoir Inspector</option>
Now in my form I want the input box (as the occupation list is very long) , for the user to type A, B etc and then the relevant occupations come up. Something like the following jsfiddle
Similar JS Fiddle
This fiddle is fine if I put all the Occupations into an array.
However the options in my .js file have values attached for use later in the web application (eg. option value='v10173')
What is the best option to get the Occupation by typing but also to make sure the value is attached.
Edited the js fiddle:
<input name="car" list="anrede" />
<input name="car-val" hidden />
<ul id="anrede"></ul>
var mycars2 = [
['Herr', 'herr'],
['thomas', 'v2345'],
];
var list = $('#anrede');
listHtml = '';
mycars2.forEach(function(item){
var option = '<li data-val="' + item[1] + '">' + item[0] + '</li>';
listHtml += option;
});
list.html(listHtml);
$('#anrede li').on('click', function(){
$('input[name="car"]').val($(this).html());
$('input[name="car-val"]').val($(this).attr('data-val'));
});
This needs jquery, and the names/values are stored in pairs inside the list.
A hidden input is used for the value.
I would suggest using data-value attribute for the "value" of selected item and array of objects, like so:
var mycars = [
{
title: 'Herr',
value: 'Herr Value'
},
{
title: 'Frau',
value: 'Frau Value'
}
];
var list = document.getElementById('anrede');
var input = document.getElementById('carList');
mycars.forEach(function(item) {
var option = document.createElement('option');
option.value = item.title;
option.dataset.value = item.value;
list.appendChild(option);
});
input.onchange = function() {
alert(document.querySelector('option[value="' + this.value + '"]').dataset.value)
}
here is the jsfiddle - https://jsfiddle.net/0jvt05L0/302/
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'm trying to make multiple buttons that when clicked they add tags like <p></p> and <b></b> to a text-field. I have already figured out how to make it work like this:
<script>
function addtxt(input) {
var obj=document.getElementById(input)
obj.value+="<p></p>"
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body')">
but instead of having multiple scripts for every different button, I'd like to know if there is a way of the JS use the element value as obj.value. Is it possible?
EDIT: i found this other code online that's even better, how can i make this new code use the element value, is there any way?
function boldText(textAreaId, link)
{
var browser=navigator.appName
var b_version=navigator.appVersion
if (browser=="Microsoft Internet Explorer" && b_version>='4')
{
var str = document.selection.createRange().text;
document.getElementById(textAreaId).focus();
var sel = document.selection.createRange();
sel.text = "<b>" + str + "</b>";
return;
}
field = document.getElementById(textAreaId);
startPos = field.selectionStart;
endPos = field.selectionEnd;
before = field.value.substr(0, startPos);
selected = field.value.substr(field.selectionStart, (field.selectionEnd - field.selectionStart));
after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
field.value = before + "<b>" + selected + "</b>" + after;
}
You may pass this to your onclick handler, and then access it's value within your function:
<script>
function addtxt(input, button) {
var obj=document.getElementById(input);
obj.value+=button.value;
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body', this)">
<input type="button" value="<b></b>" onclick="addtxt('body', this)">
Here is an example with a specific div that receives the code javascript produces.
I don't recomend adding it to a div with id body, because that word is reserved for html structural elements, so I called the destination div "addHere".
Javascript
function addtxt(e) {
console.log(e)
var dest = document.getElementById("addHere");
dest.innerHTML = e.value;
}
HTML
<input type="button" value="<p>Text</p>" onclick="addtxt(this)">
<div id="addHere"></div>
fiddle here