Below is my HTML code:
<select id="sourceNameDropdownId" label="condition " style="width:300px;">
</select>
<div id="tabs" class="selector">
</div>
Here, is my javascript code:
$("#DropdownId").change(function () {
var sid= $("#DropdownId option:selected").text();
afterclick(sid);
});
I am calling an onchange event on dropdown list, and the selected value i am passing to function afterclick
function afterclick(sid){
var tabsContainer = document.getElementById("tabs");
var crawlTab=document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList=["name1","name2","name3","name4"];
$.each(crawlList, function( index, crawlType ) {
var crawlTabElement=document.createElement("li");
crawlTabElement.innerHTML= '' +crawlType+'';
crawlTab.appendChild(crawlTabElement);
});
tabsContainer.appendChild(crawlTab);
var count=1;var tabCount=1;
$.each(crawlList, function( index, crawlType ) {
var contentCrawlTab=document.createElement("div");
contentCrawlTab.setAttribute("id",crawlType);
var p='<p>'+crawlType+'</p>';
contentCrawlTab.innerHTML=p;
tabsContainer.appendChild(contentCrawlTab);
});
$( ".selector" ).tabs();
}
This code is working fine when for the first time page gets loaded and a value is selected from the dropdown, but when i re-select value from the dropdown tabs are not getting displayed properly.
This is when i select value for the first time after page is loaded.
And when i reselect the value from dropdown its showing like this-
Is there something like reload to reload the tabs div entirely, as it seems that its appending the previous values and next time when afterclick function is called tab elements are not getting displayed properly.
I tried clearing the "tabs" div too, using **$( "#tabs " ).empty()**But it didn't worked for me.
Please help me out.
Check this working code.
$().ready(function () {
$(".selector").tabs();
$("#DropdownId").change(function () {
var sid = $("#DropdownId option:selected").text();
afterclick(sid);
});
});
function afterclick(sid) {
var tabsContainer = document.getElementById("tabs");
tabsContainer.innerHTML = '';
var crawlTab = document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList = [sid + "1", sid + "2", sid + "3", sid + "4"];
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var crawlTabElement = document.createElement("li");
crawlTabElement.innerHTML = '' + crawlType + '';
crawlTab.appendChild(crawlTabElement);
}
});
tabsContainer.appendChild(crawlTab);
var count = 1; var tabCount = 1;
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var contentCrawlTab = document.createElement("div");
contentCrawlTab.setAttribute("id", crawlType);
var p = '<p>' + crawlType + '</p>';
contentCrawlTab.innerHTML = p;
tabsContainer.appendChild(contentCrawlTab);
}
});
$(".selector").tabs('destroy');
$(".selector").tabs();
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="DropdownId" label="condition " style="width:300px;">
<option selected="selected" disabled="disabled">--Select--</option>
<option>Bilna-ID</option>
<option>IndiatimesShopping</option>
</select>
<div id="tabs" class="selector">
</div>
Related
Hi all i have code for multiple upload image, but i want only one image per upload. so I create the input file every time I clicked the upload button with the dynamic id. however I have problems checking whether the user chooses the file to upload or press the cancel button. because if the user pressed the cancel button I want to delete the input file I have created. for full sourcenya as below:
$(document).ready(function () {
$("#btnimg").click(function () {
//check input file id number
var counter = $("input[id^='upload']").length;
//add input file every btnimg clicked
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
$("#result").append(html);
//trigger to dialog open file
var upload = $('#upload_' + counter);
upload.trigger('click');
upload.on('change', function () {
console.log('change fire...');
var inputFiles = this.files;
var inputFile = inputFiles[0];
var reader = new FileReader();
reader.onload = function (evt) {
var imghtml = "<img id='img_upload_" + counter + "' src='" + evt.target.result + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
};
reader.onerror = function (event) {
alert("something: " + event.target.error.code);
};
reader.readAsDataURL(inputFile);
});
//if file not selected or user press button cancel on open dialog
//upload.remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
</body>
thank you in advance,
You can check the .length of <input type="file"> element .files property to determine if a file is selected by user
That all sounds like an xy-problem to me.
I have not (yet) got a response from you about the why you want to do it, so I will base my answer on two probable situations:
If you want to keep track of the selected Files, in order to be able to do anything with them later (e.g send them through AJAX), then use a single <input>.
At every change event, you will store the new File in an Array, from where you will also be able to do something with later on:
(function() {
// this Array will hold our files, should be accessible to the final function 'doSomething'
var savedFiles = [];
var counter = 0;
var upload = $('#upload');
upload.on('change', onuploadchange);
$("#btnimg").click(function routeClick() {
upload.trigger('click');
});
$('#endbtn').click(function doSomething() {
console.log(savedFiles);
});
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
if (!inputFile) { return; } // no File ? return
savedFiles.push(inputFile); // save this File
// don't use a FileReader here, useless and counter-productive
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
$('#endbtn').removeAttr('disabled');
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
<!-- A single input to save them all-->
<input type='file' id='upload' style='display:none;' />
</div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
<button id="endbtn" disabled>do something with saved files</button>
If, for an obscure reason, you absolutely need to keep all the filled <input> elements in your document, then create a new one only if the last one is itself filled.
$(document).ready(function() {
$("#btnimg").click(function() {
// grab previous ones
var inputs = $("input[id^='upload']");
// get the last one we created
var last = inputs.last();
var counter = inputs.length;
console.log(counter);
var upload;
// if there is no input at all, or if the last one is already filled with a File
if (!last.length || last[0].files.length) {
console.log('create new input');
upload = makeNewInput();
} else {
// use the last one
upload = last;
}
//trigger to dialog open file
upload.trigger('click');
function makeNewInput(counter) {
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
var el = $(html);
el.on('change', onuploadchange);
$('#result').append(el);
return el;
}
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
I am using bootstrap select and I encounter a problem when I want to add dynamic options using Javascript. The list is always empty. When I switch back to using HTML select the following Javascript code works perfectly.
HTML:
<select class="selectpicker" data-style="btn-lg btn-list-author"
id="author-list" data-live-search="true" title="Select Author"></select>
Javascript:
readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text){
data = JSON.parse(text);
$.each(data, function(i, v) {
alert(v.login);
var ul = document.getElementById("author-list");
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
});
With bootstrap-select you need to call the refresh method of the select-picker after you add new options.
Excerpt from bootstrap-select refresh Documentation:
.selectpicker('refresh')
To programmatically update a select with JavaScript, first manipulate
the select, then use the refresh method to update the UI to match the
new state. This is necessary when removing or adding options, or when
disabling/enabling a select via JavaScript.
Untested Example Using Your Original Code:
readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text) {
data = JSON.parse(text);
$.each(data, function(i, v) {
alert(v.login);
var ul = document.getElementById("author-list");
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
// Example call of 'refresh'
$('.selectpicker').selectpicker('refresh');
});
This lets bootstrap-select know of the data changes to the select element so it can redraw it's contents.
Working Example (with a modified version of your code)
Working Codepen with some modifications
Codepen Code:
// Had to create some stubs to replace missing code.
var repolink = 'silviomoreto/bootstrap-select';
function readDataFromGit (url, callback) {
$.get(url, callback);
}
//End of stubs
readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text) {
data = text; // Changed this because my stub is already returning parsed JSON.
var ul = document.getElementById("author-list"); // moved this out of the loop for a bit of performance improvement (not relevant to the solution.)
$.each(data, function(i, v) {
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
$('.selectpicker').selectpicker('refresh');
});
Here is a dynamic drop-down menu with grouped options from a data array:
// Example data Array list
namespace_list = [
['test1-c1', 'test2-c1', 'test3-c1', 'test4-c1', 'test5-c1', 'test6-c1'],
['test1-c2', 'test2-c2', 'test3-c2', 'test4-c2', 'test5-c2', 'test6-c2']
]
$('#pod_dropdown').selectpicker();
// Selecting selectpicker dropdown
select = document.getElementById('pod_dropdown');
for (let namespace of namespace_list) {
// Generating group name
namespace_name = namespace[0].slice(6, 8)+'-title'
// Creating the optiongroup
var optgroup = document.createElement('optgroup');
optgroup.id = namespace_name;
optgroup.label = namespace_name
// Appending optiongroup to the dropdown
select.appendChild(optgroup);
// Selecting the optiongroup
optiongroup = document.getElementById(namespace_name);
for (let pod of namespace) {
// Creating the options of the optiongroup
var opt = document.createElement('option');
opt.value = pod;
opt.innerHTML = pod;
// Appending the option to the optiongroup
optiongroup.appendChild(opt);
}
}
// Refresh the dropdwon menu
$('#pod_dropdown').selectpicker("refresh");
// Getting the value after selecting it in the UI and unselect the dropdown
function filterpod() {
let pod = $('#pod_dropdown').val().toString();
console.log(pod)
}
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- bootstrap -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- multi select dropdown -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<!-- Creatting the dropdown -->
<select id="pod_dropdown" class="selectpicker" data-style="btn btn-primary btn-sm" multiple data-live-search="true" data-width="auto"></select>
<!-- Calling the function filterpod when hide dropdown after select option -->
<script type="text/javascript">
$('#pod_dropdown').on('hide.bs.select', function(e) {filterpod();});
</script>
Im trying to update a text box when a selection changes.
Here is the code.
<script type="text/javascript">
$("#name").change(function () {
var selectedValue = $(this).val();
var result = string.substring(string.lastIndexOf(":") + 1);
document.getElementById('newname').value = result ;
});
</script>
Being an extream noob to this i dont understand why this is not working?
The #name is the dropdown list "selection" and the newname is the text box i want to update.
In the var result, string.substring, do you mean selectedValue.substring ?
<script type="text/javascript">
$("#name").change(function () {
var selectedValue = $(this).val();
var result = selectedValue.substring(selectedValue.lastIndexOf(":") + 1);
document.getElementById('newname').value = result ;
});
</script>
I'm working with a static json file. I'm using jquery to load my file into my store.
Everything loads fine.
At the side of my store, I have a categories menu, where I can filter my store items.
Because my store is items are dynamically generated, I dont seem to be able to select them with jquery.
Here is the ajax request:
<script>
$(function () {
var actionUrl = '#Url.Action("Items", "Home")';
$.getJSON(actionUrl, displayData);
function displayData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#store").append("<div class='storeItem' data-price=" + response[i].PriceScale + " data-category=" + response[i].Cat + "> <img src='#" + response[i].Cat + "' class='itemImage' alt='" + response[i].Title + "'/><span class='itemTitle'>" + response[i].Title + "</span><span class='itemDesc'><p>" + response[i].Desc + "</p></span><span class='itemPrice'>"+ response[i].Price +"</span><a href='#' class='add2cart'>ADD TO CART</a>")
}
}
else {
$("#store").append("<h5>There was a problem loading the store content.</h5>");
}
}
});
</script>
Here is the code I have tride:
<script>
$(function () {
$( "nav#catagories ul li input").on("click", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
I've also tried:
<script>
$(function () {
$(document).on("click","nav#catagories ul li input", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
In both cases the script works up untill the div.storeItem hide.
Here is the HTML that is outputed:
<div class="storeItem" data-price="med" data-category="apparel">
<img src="#apparel" class="itemImage" alt="Shirt">
<span class="itemTitle">Shirt</span>
<span class="itemDesc">
<p>A Beatiful Shirt</p>
</span>
<span class="itemPrice">23.45</span>
ADD TO CART
</div>
Maybe your problem doesn't have to do anything with items being dynamically generated. Here $(".storeItem").data("category", b).show(); you are replacing category value with value stored in b, while it seems you want to select those which has category equal to b.
Maybe this will work or at least give you the direction:
$(function () {
$(document).on("click", "nav#catagories ul li input", function () {
var checked = $(this).prop("checked");
var category = $(this).attr("id");
if (checked) {
$(".storeItem").hide()
.filter(function () {
return $(this).data("category") === category;
}).show();
}
});
});
Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});