Custom JS selector is not taking effect at ngModel - javascript

I have created a custom selector system with JS trying to make it look better. It looks perfect and changes the selector when I make it visible, but it doesn't changes my ngModel at my Angular component, keeping it at undefined. Here is my JS and HTML.
<div class="form__select">
<select id="gender" name="gender" #gender="ngModel" [(ngModel)]="user.occupation">
<option value="0">Selecciona un género</option>
<option value="1">Hombre</option>
<option value="2">Mujer</option>
<option value="3">Otro</option>
</select>
</div>
load_selector() {
const selectors: HTMLCollectionOf<Element> = document.getElementsByClassName("form__select");
document.addEventListener("click", MainScript.close_selector);
[].forEach.call(selectors, (selector) => {
const select: any = selector.getElementsByTagName("select")[0];
let replaced: HTMLElement = document.createElement("DIV");
replaced.setAttribute("class", "form__select-box");
replaced.innerHTML = select.options[select.selectedIndex].innerHTML;
selector.appendChild(replaced);
let option_parent: HTMLElement = document.createElement("DIV");
option_parent.setAttribute("class", "form__select-items");
[].forEach.call(select.options, (options) => {
let option: HTMLElement = document.createElement("DIV");
option.setAttribute("class", "form__select-item");
option.innerHTML = options.innerHTML;
option.addEventListener("click", function () {
const parent_node: any = (<HTMLElement>(<HTMLElement>(<HTMLElement>this.parentNode)).parentNode).getElementsByTagName("select")[0];
let previous_sibling: any = this.parentNode.previousSibling;
for (let i = 0; i < parent_node.length; i++) {
if (parent_node.options[i].innerHTML == this.innerHTML) {
parent_node.selectedIndex = i;
previous_sibling.innerHTML = (<HTMLElement>this).innerHTML;
let actual_selected = (<HTMLElement>(<HTMLElement>this.parentNode)).getElementsByClassName("form__select-item--selected");
[].forEach.call(actual_selected, (node) => {
node.classList.remove("form__select-item--selected");
node.classList.add("class", "form__select-item");
});
this.classList.add("form__select-item--selected");
}
}
previous_sibling.click();
});
option_parent.appendChild(option);
});
selector.appendChild(option_parent);
replaced.addEventListener("click", function (e) {
e.stopPropagation();
(<any>this).nextSibling.classList.toggle("form__select-items--active");
(<any>this).classList.toggle("form__select-box--active");
});
});
}

Related

Get Elements of a HTML div

i am building a configuration utility and having a problem with the js.
I am very new to javascript so i apologize in advance for the request for help.
in my HTML i have multiple divs that are structured like this:
<div id="options" class="opt">
<h2 id="optionName">Power Button Options</h2>
<label for="pwrAvl">Power Button Available</label>
<input type="checkbox" name="pwrAvl" id="pwrAvl"/ >
<br /><br />
<label for="pwrLabel">Power Button Label</label>
<input type="text" name="pwrLabel" id="pwrLabel"/ >
<br /><br />
<label for="pwrGraphic">Power Button Graphic</label>
<select name="pwrGraphic" id="pwrGraphic">
<option value="" selected>
----- Please select a graphic -----
</option>
<option value="power.jpeg">Power</option>
<option value="light.jpg">Light</option>
<option value="help.jpg">Help</option>
<option value="camera.jpg">Camera</option>
</select>
<br /><br />
<label for="pwrIndex">Power Button Menu Index</label>
<input type="text" name="pwrIndex" id="pwrIndex"/ >
</div>
i have between 5-10 divs that will all be structured the same way just with different labels and input values.
i tried adding all the divs to an array and then enumerate through the array but that did not work.
here is my js file what i have tried:
{
const bar = document.querySelector('options');
var opts = document.querySelectorAll('.opt')
var option = {}
var nCount = $(".opt").length;
var divArray = [];
var optName = document.getElementById('optionName');
function addArray() {
for (let i = 0; i < nCount; i++) {
divArray[i] = opts[i];
}
}
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration": {
"Options": [],
}
}
addArray()
console.log(`Divarray = ${divArray.length}`)
//The following would never work
opts.forEach(label => {
$('[id=optionName]').each(function () {
var atId = this.id;
console.log(`Searched Name = ${atId.innerHTML}`)
});
});
divArray.forEach(element => {
var name = divArray.getElementById('optionName').innerHTML;
console.log(name)
option = new SystemOptions(name, "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
});
for (let i = 0; i < nCount; i++) {
// console.log(` ${$(".opt").find("h2[id=optionName").each.text()}`)
console.log(` ${divArray[i].querySelector(optName[i]).innerHTML}`)
}
// i did this once to see if the SystemsOptions function worked
// obviosly it added the same data 7 times but i was trying to be sure the function worked and created the json objects
for (let i = 1; i < nCount; i++) {
option = new SystemOptions("Power", "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
}
let data = JSON.stringify(info, 0, 4);
console.log(data);
}
}
any help would be greatly appreciated.
not the most eloquent but this does work.
sure there are better ways:
var opts = document.querySelectorAll('.opt');
var option = {};
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration" :{
"Options": [],
}
};
for(var opt of opts)
{
var name = opt.getElementsByTagName('h2')[0].innerHTML;
let isAvailable = opt.getElementsByTagName("input")[0].value;
let optLabel = opt.getElementsByTagName("input")[1].value;
let optGraphic = opt.getElementsByTagName('select')[0].value;
let index = opt.getElementsByTagName("input")[2].value;
option = new SystemOptions(name, isAvailable, optLabel, optGraphic, index);
info.SystemConfiguration.Options.push(option);
}
console.log(`Number of options = ${opts.length}`)
let data = JSON.stringify(info, 0, 4);
console.log(data);
};

Input value is not changed on Javascript

I make shopping Cart now with vanilla javascript, html, css.
This program is when consumer click selection tag, add new tag and change count.
To Add new Tag is already working. Change count is not work. When I clicked, selectA, selectB, selectC is changed but not working on input tag.
var selectA = 0;
var selectB = 0;
var selectC = 0;
function handleOnChange(e) {
// 선택된 데이터 가져오기
let value = e.value;
let name = e.options[e.selectedIndex].text;
let itemList = document.getElementById("addItem");
var Item = document.createElement('div');
var itemName = document.createElement('div');
var itemSumA = document.createElement('input');
var itemSumB = document.createElement('input');
var itemSumC = document.createElement('input');
itemName.innerHTML = name;
if (value === "A") {
if (selectA === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumA);
itemList.appendChild(Item);
}
itemSumA.value = selectA;
} else if (value === "B") {
console.log(selectB);
if (selectB === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumB);
itemList.appendChild(Item);
}
itemSumB.value = ++selectB;
} else {
if (selectC === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumC);
itemList.appendChild(Item);
}
itemSumC.value = ++selectC;
}
document.getElementById("Sum").innerHTML = selectA * 39800 + selectB * 49800 + selectC * 59800;
}
<li class="checked">
<button class="accordion">주문 정보</button>
<div class="panel">
<p>상품 선택</p>
<select name="tent" id="tent" onchange="handleOnChange(this)">
<option value="A">A. 스피드 원터치 팝업텐트(3~4인용)</option>
<option value="B">B. 5초 원터치 텐트(3인용) (+10,000)</option>
<option value="C">C. 5초 원터치 텐트(5인용) (+20,000)</option>
</select>
<div id="addItem"></div>
</div>
</li>
I want to know why.

Alerting JS Array Selection

I have a select with options that I am putting into an array, and I am attempting to alert a specific message when you click a button, but only if the proper array[x] has been selected. However, when I click the button, regardless of the option I get the message. What am I doing wrong?
Code:
HTML:
<button id="button">Click Me</button>
<br />
<br />
<select id = "list" value = "list">
<option id="one" value="one">
one
</option>
<option id="two" value="two">
two
</option>
<option id="three" value="three">
three
</option>
</select>
JS:
var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list").selectedIndex;
for (var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}
button.onclick = function() {
if (selected = [1]) {
alert("hello");
}
};
You cannot compare arrays like this. You need to use literal number instead. JSFiddle
var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list");
for(var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}
button.onclick = function() {
if(selected.selectedIndex == 1) {
alert('hello');
}
};
If I have understood your question correctly, you need the updated value of the select:
button.onclick = function()
{
if(document.getElementById("list").selectedIndex==1) // Also change = to ==
{
alert("hello");
}
};
https://jsfiddle.net/6bs1vjva/1/

How to find Currently Selected value from this Custom HTML form Tag?

I have an element which is text box but its value is populated from another hidden select element.
<input type="text" id="autocompleteu_17605833" style="box-shadow: none; width: 119px;" class="mobileLookupInput ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<select id="u_17605833" name="u_17605833" style="visibility: hidden">
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
var mySelObju_17605833 = document.getElementById("u_17605833");
$(function () {
var availableTagsu_17605833 = new Array();
for (var i = 0; i < mySelObju_17605833.options.length; i++) {
if (mySelObju_17605833.options[i].text != 'Other') {
availableTagsu_17605833[i] = mySelObju_17605833.options[i].text;
}
}
$("#autocompleteu_17605833").width($(mySelObju_17605833).width() + 5);
availableTagsu_17605833 = $.map(availableTagsu_17605833, function (v) {
return v === "" ? null : v;
});
$("#autocompleteu_17605833").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
var a = $.grep(availableTagsu_17605833, function (item, index) {
var items = item.split(" ");
for (i = 0; i < items.length; i++) {
if (matcher.test(items[i])) return matcher.test(items[i]);
}
return matcher.test(item);
});
response(a);
},
close: function (event, ui) {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
}
});
});
$("#autocompleteArrowu_17605833").click(function () {
$("#autocompleteu_17605833").autocomplete("search");
$("#autocompleteu_17605833").focus();
});
$("#autocompleteu_17605833").focusout(function () {
for (var i = 0, sL = mySelObju_17605833.length; i < sL; i++) {
if (mySelObju_17605833.options[i].text.toLowerCase() == $("#autocompleteu_17605833").val().toLowerCase()) {
mySelObju_17605833.selectedIndex = i;
$("#errorTDu_17605833").html("");
break;
}
mySelObju_17605833.selectedIndex = 0;
$("#errorTDu_17605833").html("Error: Invalid Input");
}
$("#autocompleteu_17605833").trigger("onchange")
//$(this).autocomplete("close");
});
I want to find value selected in the hidden select box!
I tried to do the following
$("#autocompleteu_17605833").on("click", function (event) {
$((this.id).substring((this.id).indexOf("_") - 1)).attr("onchange", function (event) {
var selece = this.value;
alert(selece);
});
});
$("#autocompleteu_17605833").next().on("click", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Click on Arrow" + selectedValue);
});
$("#autocompleteu_17605833").on("change", function (event) {
var selectedValue = document.getElementById((this.id).substring((this.id).indexOf("_") - 1)).value;
alert("Changing the value" + selectedValue);
});
what I'm getting is older value where as I need the current assigned value.
How to achieve this??
WORKING DEMO
If am not wrong you want the selected value for this you can use select method
select:function(event,ui) {
alert("You have selected "+ui.item.label);
alert("You have selected "+ui.item.value);
}
This is a simple piece of code that will work as you required.
function result(){
document.getElementById("result").innerHTML= document.getElementById("u_17605833").value;
}
<html>
<head>
</head>
<body>
<div>
<select id="u_17605833" name="u_17605833" >
<option value="127468">Virginia</option>
<option value="127469">Washington</option>
<option value="127470">West Virginia</option>
<option value="127471">Wisconsin</option>
<option value="127472">Wyoming</option>
</select>
<input type="button" value="Show the result" onclick="result()"/>
</div>
<div id="result"></div>
</body>
</html>

disable checkbox when i select

i have a problem in html and javascript. i have tried different approach but everything didnt worked. so this is my sample code.
<select id = "testselect" name = "testselect">
<option> </option>
<option id = "o1" name = "testselect" value = "1" onselect='document.getElementById("os1").disabled = true;'> 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>
ok, that's the code. what i want to happen is, when i selected o1(option id), os1(checkbox id) must be disabled and when i selected o2(option id), os2(checkbox id) must be disabled, and so on. so can anyone help me?
Try this:
Using plain javascript:
var select;
function changeIt() {
var allCheckboxes = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < allCheckboxes.length; i++) {
allCheckboxes[i].removeAttribute('disabled');
}
var value = select.options[select.selectedIndex].value;
var checkBox = document.querySelector('input[id=os' + value + ']');
checkBox.disabled = true;
}
window.onload = function () {
select = document.getElementById('testselect');
select.onchange = changeIt;
changeIt();
}
Demo
Using jQuery:
$('select').change(function () {
$('input[type=checkbox]').removeAttr('disabled');
$('input[id=os' + this.value + ']').attr('disabled', true);
});
Demo
My own suggestion would be to move the event-handling outside of the HTML (for ease of future maintenance and change), and take the following approach:
function disableCheck(event) {
// get the element that was the target of the 'change' event:
var that = event.target,
/* find the option tags, and retrieve the option that was selected
from that collection (nodeList) of elements: */
opt = that.getElementsByTagName('option')[that.selectedIndex];
/* find the element whose 'id' is equal to the 'id' of the 'option'
once the 's' is inserted, and set the 'disabled' property to 'true': */
document.getElementById(opt.id.replace('o', 'os')).disabled= true;
}
// bind the onchange event-handler to the element with the id of 'testselect':
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
To toggle which elements are disabled (rather than simply increase the number of disabled elements):
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o','os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++){
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
Well, this is ugly...and suggests I really need to rethink the approach above, however it does work (though it doesn't properly support IE as yet). This uses a trigger function which is fired upon the window.load event which triggers the change event from the select element-node:
function trigger(event, source) {
var newEvent;
if (document.createEvent) {
newEvent = document.createEvent("HTMLEvents");
newEvent.initEvent(event, true, true);
} else {
newEvent = document.createEventObject();
newEvent.eventType = event;
}
newEvent.eventName = event;
if (document.createEvent) {
source.dispatchEvent(newEvent);
} else {
source.fireEvent("on" + newEvent.eventType, newEvent);
}
}
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o', 'os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++) {
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
window.addEventListener('load', function(){
trigger('change', document.getElementById('testselect'));
});
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
onselect should go into the select
<script>
function onSelect(obj){
var x = document.getElementsByName("othser[]");
for (var i in x) x[i].disabled = false;
document.getElementById("os"+obj.value).disabled=true;
}
</script>
<select id = "testselect" name = "testselect" onchange='onSelect(this)'>
<option> </option>
<option id = "o1" name = "testselect" value = "1" > 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>

Categories

Resources