I have many list of radio button in a ng-repeat.
I've succeded for get the selected item.
Now I try to set the default value of the radio.
Can some one help me please. Here my code for the button.
Thank's
VariableRadioArr2 = [{"id":"21","libelle":"P15m","type":"radio","valeur_1":"Oui","valeur_2":"Non","valeur_3":"","valeur_4":"","valeur_5":"","valeur_6":"","valeur_7":"","valeur_8":"","valeur_9":"","valeur_10":""},{"id":"25","libelle":"Surface (m²)","type":"input","valeur_1":"","valeur_2":"","valeur_3":"","valeur_4":"","valeur_5":"","valeur_6":"","valeur_7":"","valeur_8":"","valeur_9":"","valeur_10":""},{"id":"36","libelle":"p16","type":"radio","valeur_1":"Oui","valeur_2":"Non","valeur_3":"","valeur_4":"","valeur_5":"","valeur_6":"","valeur_7":"","valeur_8":"","valeur_9":"","valeur_10":""}]
$scope.itemGroups = VariableRadioArr2;
console.log(VariableRadioArr2);
//$scope.selected = 1;
$scope.VariableRadioToggle2 = true;
$scope.clickedVariableRadio2 = function(test)
{
$scope.clickedVariableRadio2_select = JSON.parse(JSON.stringify($scope.itemGroups));
}
if(VariableRadioArr2.length == 0)
{
$scope.clickedVariableRadio2_select = [];
$scope.VariableRadioToggle2 = false;
}
<ion-list id="page-list7" ng-show="VariableRadioToggle2">
<div ng-repeat="itemGrp in itemGroups">
<ion-item class="item-divider" id="page-list-item-divider32">{{itemGrp.name}}</ion-item>
<ion-toggle name="{{itemGrp.name}}" ng-click="clickedVariableRadio2(portion.selected)" ng-repeat="(key,portion) in itemGrp.Portions" ng-model="itemGrp.selected_item" ng-true-value="'{{key}}'" ng-false-value="">{{portion.name}}</ion-toggle>
</div>
</ion-list>
Here I'm doing a loop from 1-10 to copy the values into a new object and delete the old ones.
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
var Variable = [{"id":"21","libelle":"P15m","type":"radio","valeur_1":"Oui","valeur_2":"Non","valeur_3":"","valeur_4":"","valeur_5":"","valeur_6":"","valeur_7":"","valeur_8":"","valeur_9":"","valeur_10":""},{"id":"25","libelle":"Surface (m²)","type":"input","valeur_1":"","valeur_2":"","valeur_3":"","valeur_4":"","valeur_5":"","valeur_6":"","valeur_7":"","valeur_8":"","valeur_9":"","valeur_10":""},{"id":"36","libelle":"p16","type":"radio","valeur_1":"Oui","valeur_2":"Non","valeur_3":"","valeur_4":"","valeur_5":"","valeur_6":"","valeur_7":"","valeur_8":"","valeur_9":"","valeur_10":""}];
// Create sub object for all values
// and delete the old values
for (i = 0; i < Variable.length; i++) {
Variable[i].values = {};
Variable[i].selected = '';
for (v = 1; v < 11; v++) {
if(Variable[i]['valeur_'+v] != undefined){
Variable[i].values['valeur_'+v] = Variable[i]['valeur_'+v];
delete Variable[i]['valeur_'+v];
}
}
}
$scope.itemGroups = Variable;
// Set defaults
// By index
$scope.itemGroups[1].selected = 'valeur_4';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="itemGrp in itemGroups">
<div>{{itemGrp.libelle}}</div>
<label ng-repeat="(key, value) in itemGrp.values">
<input type="radio" name="{{itemGrp.id}}" ng-model="itemGrp.selected" ng-value="key">{{value}}
</label>
</div>
</div>
Related
I am trying to add dropdown list dynamically to a WebApp using google appscript. I wrote a few lines of javascript code in the client side to communicate the server side to fetch the data from google-sheets. After a lot of trying, I'm somewhat successful. However, it looks like, whenever I click on the "Add Product" button, for first 1-2 times the array from which the dropdown is generated is empty. As a result the dropdown remains blank. However after 1 or 2 blank dropdowns the it starts working as it's suppose to.
What am I doing wrong ?
I have 3 files-
form.html
code.gs
js_script.html
Link to the google sheet
Content of form.html-
<body>
<div class="container">
<div class = "row">
<h1>Order Form</h2>
</div> <!-- end of row -->
<div class = "row">
<input id="orderno" type="text" class="validate">
<label for="orderno">Order Number</label>
</div> <!-- end of row -->
<div class = "row">
<input id="clientname" type="text" class="validate">
<label for="clientname">Client Name</label>
</div> <!-- end of row -->
<div class = "row">
<input id="clientaddr" type="text" class="validate">
<label for="clientaddr">Client Address</label>
</div> <!-- end of row -->
<div class = "row">
<input id="clientphone" type="text" class="validate">
<label for="clientphone">Client Phone Number</label>
</div> <!-- end of row -->
<div class = "row">
<input id="ordertype" type="text" class="validate">
<label for="ordertype">Order Type</label>
</div> <!-- end of row -->
<div id="productsection"></div>
<div class = "row">
<button id="addproduct">Add Product</button>
</div> <!-- end of row -->
<div class = "row">
<button id="submitBtn">Submit</button>
</div> <!-- end of row -->
</div> <!-- End of "container" class -->
<?!= include("js_script"); ?>
</body>
Content of code.gs
const ssID = "1YKZYgKctsXU3DKTidVVPUhmPXUkzjjocaiMz1S76JAE";
const ss = SpreadsheetApp.openById(ssID);
function doGet(e){
Logger.log(e);
return HtmlService.createTemplateFromFile("form").evaluate();
}
function include(fileName){
return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}
function appendDataToSheet(userData){
const ws = ss.getSheetByName("orders");
ws.appendRow([new Date(), userData.orderNumber, userData.clientName, userData.clientAddress, userData.clientPhone, userData.orderType, userData.products].flat());
}
function getOptionArray(){
const ws = ss.getSheetByName("product_list");
const optionList = ws.getRange(2, 1, ws.getRange("A2").getDataRegion().getLastRow() - 1).getValues()
.map(item => item[0]);
return optionList;
}
function logVal(data){
Logger.log(data);
}
Content of js_script.html
<script>
let counter = 0;
let optionList = [];
document.getElementById("submitBtn").addEventListener("click", writeDataToSheet);
document.getElementById("addproduct").addEventListener("click", addInputField);
function addInputField(){
counter++;
// The idea is, everytime when "add product" button is clicked, the following element must be added to the "<div id="productoption></div>" tag.
// <div class="row">
// <select id="productX">
// <option>option-X</option>
// </select>
// </div>
const newDivTag = document.createElement('div');
const newSelectTag = document.createElement('select');
newDivTag.class = "row";
newSelectTag.id = "product" + counter.toString();
google.script.run.withSuccessHandler(updateOptionList).getOptionArray();
google.script.run.logVal(optionList); // This is just to test the optionList array if it's updated or not
for(let i = 0; i < optionList.length; i++){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionList[i];
newOptionTag.value = optionList[i];
newSelectTag.appendChild(newOptionTag);
}
newDivTag.appendChild(newSelectTag);
document.getElementById('productsection').appendChild(newDivTag);
}
function writeDataToSheet(){
const userData = {};
userData.orderNumber = document.getElementById("orderno").value;
userData.clientName = document.getElementById("clientname").value;
userData.clientAddress = document.getElementById("clientaddr").value;
userData.clientPhone = document.getElementById("clientphone").value;
userData.orderType = document.getElementById("ordertype").value;
userData.products = [];
for(let i = 0; i < counter; i++) {
let input_id = "product" + (i+1).toString();
userData.products.push(document.getElementById(input_id).value);
}
google.script.run.appendDataToSheet(userData);
}
function updateOptionList(arr){
optionList = arr.map(el => el);
}
</script>
About your current issue of However, it looks like, whenever I click on the "Add Product" button, for first 1-2 times the array form which the dropdown is generated is empty. As a result the dropdown remains blank. However after 1 or 2 blank dropdowns the it starts working as it's suppose to., when I saw your script, I thought that the reason for your issue might be due to that google.script.run is run with the asynchronous process. If my understanding is correct, how about the following modification?
In this case, your js_script.html is modified.
Modified script:
<script>
let counter = 0;
// let optionList = []; // Removed
document.getElementById("submitBtn").addEventListener("click", writeDataToSheet);
document.getElementById("addproduct").addEventListener("click", addInputField);
// Modified
function addInputField(){
counter++;
const newDivTag = document.createElement('div');
const newSelectTag = document.createElement('select');
newDivTag.class = "row";
newSelectTag.id = "product" + counter.toString();
google.script.run.withSuccessHandler(arr => {
const optionList = updateOptionList(arr);
google.script.run.logVal(optionList);
for(let i = 0; i < optionList.length; i++){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionList[i];
newOptionTag.value = optionList[i];
newSelectTag.appendChild(newOptionTag);
}
newDivTag.appendChild(newSelectTag);
document.getElementById('productsection').appendChild(newDivTag);
}).getOptionArray();
}
function writeDataToSheet(){
const userData = {};
userData.orderNumber = document.getElementById("orderno").value;
userData.clientName = document.getElementById("clientname").value;
userData.clientAddress = document.getElementById("clientaddr").value;
userData.clientPhone = document.getElementById("clientphone").value;
userData.orderType = document.getElementById("ordertype").value;
userData.products = [];
for(let i = 0; i < counter; i++) {
let input_id = "product" + (i+1).toString();
userData.products.push(document.getElementById(input_id).value);
}
google.script.run.appendDataToSheet(userData);
}
// Modified
function updateOptionList(arr){
return arr.map(el => el); // I cannot understand this mean.
}
</script>
or, in this case, updateOptionList might not be required to be used as follows.
<script>
let counter = 0;
// let optionList = []; // Removed
document.getElementById("submitBtn").addEventListener("click", writeDataToSheet);
document.getElementById("addproduct").addEventListener("click", addInputField);
// Modified
function addInputField(){
counter++;
const newDivTag = document.createElement('div');
const newSelectTag = document.createElement('select');
newDivTag.class = "row";
newSelectTag.id = "product" + counter.toString();
google.script.run.withSuccessHandler(optionList => {
google.script.run.logVal(optionList);
for(let i = 0; i < optionList.length; i++){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionList[i];
newOptionTag.value = optionList[i];
newSelectTag.appendChild(newOptionTag);
}
newDivTag.appendChild(newSelectTag);
document.getElementById('productsection').appendChild(newDivTag);
}).getOptionArray();
}
function writeDataToSheet(){
const userData = {};
userData.orderNumber = document.getElementById("orderno").value;
userData.clientName = document.getElementById("clientname").value;
userData.clientAddress = document.getElementById("clientaddr").value;
userData.clientPhone = document.getElementById("clientphone").value;
userData.orderType = document.getElementById("ordertype").value;
userData.products = [];
for(let i = 0; i < counter; i++) {
let input_id = "product" + (i+1).toString();
userData.products.push(document.getElementById(input_id).value);
}
google.script.run.appendDataToSheet(userData);
}
</script>
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
Reference:
Class google.script.run (Client-side API)
I have some html elements like this:
<div class="items">
<div class="item" data-opt1="val1" data-opt2="val2,val3">Item 1</div>
<div class="item" data-opt1="val4" data-opt2="val2,val5">Item 2</div>
<div class="item" data-opt1="val1" data-opt2="val3,val6">Item 3</div>
<div class="item" data-opt1="val7" data-opt2="val3,val5">Item 4</div>
</div>
and 2 variables to be used as filters, one array of options and one search string like this:
Example 1
var srcString = "val";
var filters = [
'opt1' : ['val1'],
'opt2' : ['val2','val6']
];
In this example item1 and item3 should be visible, item2 and item4 not visible.
Example 2
var srcString = "value";
var filters = [
'opt1' : ['val1'],
'opt2' : ['val2','val6']
];
All items shouldn't be visible, because var srcString contain a word that are not present in any of the data attributes.
Example 3
var srcString = "val6";
var filters = [];
Only item3 should be visible.
Example 4
var srcString = "";
var filters = [
'opt1' : ['val1','val7'],
'opt2' : ['val5']
];
Only item4 should be visible, because item1 and item3 (even if have opt1=val1) not have val5 in opt2.
Example 5
var srcString = "";
var filters = [
'opt1' : ['val1','val7']
];
items: 1,3,4 should be visible.
I was able to make all of these filters work one by one, but problems comes when I try to combinate all of them.
Code for search:
$(".item").each(function(){
var item = $(this);
if (item.data('opt1').toLowerCase().indexOf(srcVal) >= 0
|| item.data('opt2').toLowerCase().indexOf(srcVal) >= 0){
item.removeClass('d-none');
}else{
item.addClass('d-none');
}
});
Code for single filter:
var selectedOptions = filters['opt2'];
$(".item").each(function(){
var item = $(this);
let _options = item.data('opt2') + '';
_options = _options.split(",");
let found = _options.some(r=> selectedOptions.includes(r));
if(found==true){
item.removeClass('d-none');
}else{
item.addClass('d-none');
}
})
Any help is appreciate
Adapting your existing code, you can move the 2nd check inside the pass of the 1st check.
There's a few extra checks needed such as checking that .opt2 exists and has values, but these are simple checks.
$(".item").each(function() {
var item = $(this);
if (item.data('opt1').toLowerCase().indexOf(srcString) >= 0 ||
item.data('opt2').toLowerCase().indexOf(srcString) >= 0) {
item.removeClass('d-none');
var selectedOptions = filters['opt2'];
if (selectedOptions != null) {
let _options = item.data('opt2') + '';
_options = _options.split(",");
if (_options.length > 0) {
let found = _options.some(r => selectedOptions.includes(r));
if (found == true) {
item.removeClass('d-none');
} else {
item.addClass('d-none');
}
}
}
} else {
item.addClass('d-none');
}
});
Fiddle: https://jsfiddle.net/7t26n3pj/
note: this uses OPs code as provided so does not match their examples exactly as missing check for opt1
You can remove the if (_available_) continue to reduce code indentation by moving the check into a separate function and return true/false for pass/not pass - this will also allow you to add new filters going forward.
function applyFilter(filter) {
$(".item").each(function() {
var item = $(this);
if (passesFilter(item, filter))
item.removeClass('d-none');
else
item.addClass('d-none');
})
}
function passesFilter(item, filter) {
if (item.data('opt1').toLowerCase().indexOf(filter.srcString) < 0 &&
item.data('opt2').toLowerCase().indexOf(filter.srcString) < 0)
return false;
var selectedOptions = filter.filters['opt2'];
if (selectedOptions == null) return true;
let _options = item.data('opt2') + '';
_options = _options.split(",");
if (_options.length === 0) return true;
let found = _options.some(r => selectedOptions.includes(r));
return found;
}
// Examples
$("button").click(function() {
var filter = $(this).data("filter");
console.log(filter);
applyFilter(filter);
});
.d-none { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="items">
<div class="item" data-opt1="val1" data-opt2="val2,val3">Item 1</div>
<div class="item" data-opt1="val4" data-opt2="val2,val5">Item 2</div>
<div class="item" data-opt1="val1" data-opt2="val3,val6">Item 3</div>
<div class="item" data-opt1="val7" data-opt2="val3,val5">Item 4</div>
</div>
<button type='button' data-filter='{"srcString":"val","filters":{"opt1":["val1"],"opt2":["val2","val6"]}}'>
test 1
</button>
<button type='button' data-filter='{"srcString":"value","filters":{"opt1":["val1"],"opt2":["val2","val6"]}}'>
test 2
</button>
<button type='button' data-filter='{"srcString":"val6","filters":{}'>
test 3
</button>
<button type='button' data-filter='{"srcString":"","filters":{"opt1":["val1", "val7"],"opt2":["val5"]}}'>
test 4
</button>
<button type='button' data-filter='{"srcString":"","filters":{"opt1":["val1", "val7"]}}'>
test 5
</button>
I am developing an application using Angular 2.. In my application I am using barcode scanner to scan in the text field and storing those items in the array.
When I scan the item get added to array, but when I scan another item the old item it replace the old value in array.
Below is the piece of code which I am using. Please help me if you see any fix for the weird issue.
import { Component,ViewChild,Input, Output,OnInit,ChangeDetectorRef } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HeaderComponent } from '../common/header.component';
//import { SaleCart } from '../model/SaleCart';
//import * as $ from "jquery";
declare var jQuery: any
#Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./posapp.component.css']
})
export class TestComponent implements OnInit{
title = 'Treewalker POS';
public cartItems = [];
public query;
public filteredList = [];
public products = [{"id":"3","name":"Pears Soap Original 75gm","sku":"89675432189","price":"32.00","special_price":"32.00","qty":null,"barcode":"89675432189","tax":"5","discount":"0"},{"id":"1","name":"Rin","sku":"1111111111111","price":"11.00","special_price":"11.00","qty":"10.000","barcode":"1111111111111","tax":"5","discount":"0"},{"id":"2","name":"Test 1","sku":"23456","price":"10.00","special_price":"10.00","qty":"10.000","barcode":"23456","tax":"5","discount":"0"}];
constructor() {
}
ngOnInit() {
}
add(item) {
/* check the items in the json data */
let flag = false;
var foodItem = {};
for (let product of this.products) {
if(product.barcode == item) {
flag = true;
foodItem['ctr'] = 1;
foodItem['item'] = product;
break;
}
}
let localCart = [];
if(sessionStorage.getItem("cart")){
localCart = JSON.parse(sessionStorage.getItem("cart"));
//console.log(JSON.stringify(localCart));
}
//console.log("food "+JSON.stringify(this.cart));
if(flag && localCart.length) {
let exist = 0;
for(let i=0; i < localCart.length; i++) {
if(localCart[i].item.barcode == item) {
localCart[i].ctr = parseInt(localCart[i].ctr) + 1;
//console.log("#### "+this.cart[i].ctr+" --- "+item);
exist = 1;
}
}
if(!exist){
localCart.push(foodItem);
}
sessionStorage.setItem("cart",JSON.stringify(localCart));
//this.barcode = "";
}else if(flag){
localCart.push(foodItem);
sessionStorage.setItem("cart",JSON.stringify(localCart));
}
//this.cart = JSON.parse(sessionStorage.getItem("cart"));
//this.itemsCnt = localCart.length;
//console.log("--- "+this.itemsCnt);
console.log(JSON.parse(sessionStorage.getItem('cart')));
//this.onScanProduct.emit(localCart);
}
filter(e) {
//e.preventDefault();
if (this.query !== ""){
this.filteredList = this.products.filter(function(el){
if(el.barcode.toLowerCase() == this.query.toLowerCase()) {
return el.barcode.toLowerCase() == this.query.toLowerCase();
}else{
return el.barcode.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
}
}.bind(this));
/* scanned item will be added to the cart */
console.log(this.filteredList.length);
if(this.filteredList.length > 0 && e.which == 13){
//console.log(JSON.stringify(this.filteredList));
for (let product of this.filteredList) {
//console.log(filter.barcode+"=="+this.query);
if(product.barcode == this.query) {
this.add(product.barcode);
jQuery('#barcode').val("");jQuery('#barcode').focus();
this.filteredList = [];
}
}
}
}else{
this.filteredList = [];
}
}
}
Below is the html template
<div class="content-wrapper">
<section class="content">
<form>
<div class="row">
<!-- sales item add window -->
<!-- end -->
<div class="col-sm-4">
<div class="box box-primary">
<div class="box-body">
<div class="form-group">
<div class="row">
<div class="col-md-9">
<!--<input type="text" class="form-control" id="barcode" name="barcode" [(ngModel)]="barcode" (ngModelChange)="add($event)"
placeholder="Enter item code or scan the barcode" autocomplete="off" />-->
<input id="barcode" type="text" class="form-control validate filter-input" name="query" [(ngModel)]="query" (keyup)="filter($event)" placeholder="Enter item code or scan the barcode" autocomplete="off" [ngModelOptions]="{standalone: true}">
</div>
<div class="suggestions" *ngIf="filteredList.length > 0">
<ul>
<li *ngFor="let item of filteredList" >
<a (click)="select(item)" href="javascript:;">{{item.barcode}} {{item.name}}</a>
</li>
</ul>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-primary" (click)="createnewproduct(newproduct)">New Product</button>
</div>
</div>
</div>
</div> <!-- end of box body -->
</div>
</div>
</div><!-- end of row -->
</form>
</section>
</div>
Below is the input field which is being used to scan the barcode
<input id="barcode" type="text" class="form-control validate filter-input" [(ngModel)]="query" (keyup)="filter()" placeholder="Enter item code or scan the barcode" autocomplete="off">
I am assuming you are using only the function add. I tried to implement in a javascript like in the following code but I am pretty sure you are referencing that object somewhere else and you are changing it. That's my conclusion but I might be wrong.
var factoryP = (function(){
function P() {
this.cart = [];
this.products = [{'barcode': 1, 'name': 'a'}, {'barcode': 1, 'name': 'b'}]
}
function add(item) {
/* check the items in the json data */
//console.log("cart length "+JSON.stringify(this.cart));
let flag = false;
var foodItem = {};
for (let product of this.products) {
if(product.barcode == item) {
//console.log("check "+item);
flag = true;
foodItem['ctr'] = 1;
foodItem['item'] = product;
break;
}
}
if(flag && this.cart.length) {
let exist = 0;
for(let i=0; i < this.cart.length; i++) {
if(this.cart[i].item.barcode == item) {
//console.log("Same product");
this.cart[i].ctr = parseInt(this.cart[i].ctr) + 1;
exist = 1;
}
}
if(!exist){
console.log(foodItem);
this.cart.push(foodItem);
}
}else if(flag){
console.log("step 4 "+item);
this.cart.push(foodItem);
}
}
P.prototype.add = add;
return new P();
});
instanceP = factoryP();
instanceP.add(1);
instanceP.add(1);
instanceP.add(1);
instanceP.add(2);
console.log(instanceP.cart[0].ctr)
//output 3
instanceP.cart[1].ctr
//output 1
Check your code here. Every time you are initializing the foodItem array with empty array. So whenever code will call add method, it will first empty your foodItem array.
Please check my comment in your code below:
add(item) {
let flag = false;
//Akshay: You need to make your changes here. Initialize your foodItem array out of this scope
var foodItem = {};
for (let product of this.products) {
if(product.barcode == item) {
//console.log("check "+item);
flag = true;
foodItem['ctr'] = 1;
foodItem['item'] = product;
break;
}
}
I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />
I'm having issues with adding and removing items from my list on click. The removal function works only once.
HTML
<h1 id="show-list></h1>
<ul id="my-list>
<li data-itemname="C1">C1</li>
<li data-itemname="B23">B23</li>
<li data-itemname="D52">D54</li>
...
JS
$('#my-list').each(function() {
var $widget = $(this),
$itemname = $(this).attr('data-itemname'),
...
$widget.on('click', function() {
$currentlist = document.getElementById('show-list').innerHTML;
// create current list array
var str = $currentlist; // C1, B23, D54, etc
var array = str.split(',');
// convert item number to string
var itemtocheck = $itemname.toString(); // works OK
// check if value in array
var result = $.inArray(itemtocheck, array); // so far so good
if (result == 0) {
selecteditems = $currentlist.replace(itemtoremove+',', '');
$('#show-list').html(selecteditems); // Works only once
return false;
} else {
$('#show-list').append($itemname+','); // will add OK
return false;
}
});
...
Also I feel that this function can be simplified?
EDIT: Rewrote it
var $showList = $('#show-list');
$('#my-list').find('li').click(function () {
var $this = $(this);
var itemName = $this.data('itemname');
var showListText = $showList.text();
var showListItems = showListText.split(',');
var itemIndex = showListItems.indexOf(itemName);
if (itemIndex > -1) {
// remove item
showListItems.splice(itemIndex, 1);
} else {
// append item
showListItems.push(itemName);
}
showListText = showListItems.filter(function (a) { return !!a; }).join(',');
$showList.text(showListText);
});
jsfiddle
EDIT 3:
Just from a best practices stand point I prefix jQuery objects with $ and nothing else. I feel like it makes the code much more readable and allows you to give a variable a "type" so you always know what's what.
Is this what you are needing? I'd skip converting to an array first. Also, what's $itemname in your code?
<html>
<head>
<script>
function removeItemFromList(listName, itemName) {
var selectobject=document.getElementById(listName);
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == itemName) {
selectobject.remove(i);
}
}
}
function addItemToList(listName, itemName, itemValue) {
var selectobject=document.getElementById(listName);
var found = false;
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == itemValue) {
found = true;
// already in list, don't re-add
break;
}
}
if (!found) {
var option = document.createElement("option");
option.text = itemName;
option.value = itemValue;
selectobject.add(option);
}
}
</script>
</head>
<body>
<select id="show-list">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
<input type="button" value="remove volvo" onclick="removeItemFromList('show-list', 'volvo');" />
<input type="button" value="remove saab" onclick="removeItemFromList('show-list', 'saab');" />
<input type="button" value="add delorean" onclick="addItemToList('show-list', 'DeLorean', 'delorean');" />
</body>
</html>