i am currently trying to create unique ids in html.
However, i am not sure if this below codes is creating unqiue ids and being assigned to the element itself in the html or just creating unqiue ids only.
Please help me out. If this is not assigned them in html, how am i supposed to do them?
var abcElements = document.querySelectorAll('.like');
for (var i = 0; i < abcElements.length; i++){
abcElements[i].id = 'like_' + i;
alert(abcElements[i].id);
}
Updates:
I have include all the related codes in
<td><a onclick="return confirm(this)"><input class="switch" data-toggle="toggle" data-on="like" data-off="unlike" data-onstyle="danger" data-width="90" data-height="30" type="checkbox"></a></td>
<td style="display:none;"><div class="like">${like}</div></td>
Javascript
var abcElements = document.querySelectorAll('.switch');
var status = document.querySelectorAll('.like');
alert(status.length);
for (var i = 0; i < abcElements.length; i++)
{
abcElements[i].id = 'switch_' + i;
alert(abcElements[i].id);
for (var j = 0; j < status.length; j++)
{
status[j].id = 'like_' + j;
var statusText = $('#'+status[j].id+'').html();
alert(statusText);
if(statusText == 'true' )
{
$('#'+abcElements[i].id+'').bootstrapToggle('on');
}
}
}
Based on your code I assume this is what you want?
$("table tr").each(function(row) {
var $row = $(this);
var statusText = $row.find(".like").html();
console.log("status: " + statusText);
if (statusText == "true") {
// $row.find("input.switch").bootstrapToggle('on');
$row.find("input.switch").prop("checked", ($row.find(".like").html() === "true"));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span><input class="switch" type="checkbox">switch 1</span>
</td>
<td style="display:none;">
<div class="like">false</div>
</td>
</tr>
<tr>
<td>
<span><input class="switch" type="checkbox">switch 2</span>
</td>
<td style="display:none;">
<div class="like">true</div>
</td>
</tr>
</table>
I realized i am assigning the ids for individual divs. I just need to move one of the loops outside that's all.
Related
I'm trying to work on a website currently that displays pictures with the help of java-script. The way that I have this website set up at the moment, an image is displayed above numbered photo links. Instead of having numbers listed below the pictures, I'd like to have the numbers be thumbnails of the pictures. Is it possible to replace them with images? Any help is appreciated.
This is what I have so far:
var photos = new Array();
var photoindex = 0;
photos[0] = "images/piano.jpg";
photos[1] = "images/guitar.jpg";
photos[2] = "images/studio.jpg";
photos[3] = "images/sheetmusic.jpg";
function backward() {
if (photoindex > 0) {
document.images.p.src = photos[--photoindex];
}
}
function forward() {
if (photoindex < photos.length - 1) {
document.images.p.src = photos[++photoindex];
}
}
for (i = 0; i < photos.length; i++) {
document.write("" + i + " ");
}
function goto(n) {
if (n < photos.length && n >= 0) {
photoindex = n;
document.images.p.src = photos[photoindex];
}
}
<br>
<div style="text-align:center;left:5px;">
<table width="250" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" align="center" valign="top">
<img src="images/weloveweb.png" name="p" width="250" height="188" id="p" />
</td>
</tr>
<tr>
<td valign="top"><<
</td>
<td valign="top" style="text-align: center">
</td>
<td valign="top" style="text-align: right">>>
</td>
</tr>
</table>
</div>
Since your thumbnail urls are stored in the photos array, what you need to do to display a thumbnail instead of its index is to create an img tag with a src attribute containing each thumbnail's url (i.e. photos[i]).
Change:
for (i = 0; i < photos.length; i++) {
document.write("" + i + " ");
// ------------------------------------------------------------^ change this `i`
}
Into:
for (i = 0; i < photos.length; i++) {
document.write("" + "<img src=" + photos[i] + "/> ");
}
I am working on a multibox as a part of my codeigniter based project, here I am trying to move the values across the boxes using custom js code shared below
The values shown in first box are fetched from db when page loads and used to move the required values to second box using javascript. My goal it that the values already moved to second box should not be visible in the first box after saving the data and at the same time source data for the first box should not be altered.
Right now I am able to select the values to second box and save successfully but when I load the page again after saving I am seeing the moved values in the fist box and this is visually creating duplication of values and would confuse the user. On the other hand if I try to move back the values to the first box which is creating a conflict while saving the data.
Is there any way I could change my code so that moved values will not be available in the first box again
HTML version of multibox
<fieldset class="emp_contact">
<legend>Area Allocation</legend>
<div class="form-group input-group">
<table width="100%" border="0" cellpadding="10" cellspacing="10" style="border:1px solid #ccc">
<tr>
<td width="40%">
<p>Available Areas</p>
</td>
<td width="12%"> </td>
<td width="40%">
<p>Selected Areas</p>
</td>
</tr>
<tr>
<td valign="top" id="myarea_list">
<?php echo $aval_area_list ?>
</td>
<select name="aval_id_temp" id="aval_id_temp" multiple style="display:none"></select>
<td>
<table width="100%" border="0">
<tr>
<td align="center">
<input type="Button" value=">>" onClick="SelectMoveRows_all(document.form.avail_area, document.form.selec_area)">
<br>
<br />
<input type="Button" value=">" onClick="SelectMoveRows(document.form.avail_area, document.form.selec_area)">
<br>
<br>
<input type="Button" value="<<" onClick="SelectMoveRows_all(document.form.selec_area, document.form.avail_area)">
<br>
<br>
<input type="Button" value="<" onClick="SelectMoveRows(document.form.selec_area, document.form.avail_area)">
</td>
</tr>
<tr>
<td align="center"> </td>
</tr>
</table>
</td>
<td valign="top">
<?php echo $sel_area_list ?>
<select name="sel_id_temp" id="sel_id_temp" multiple style="display:none"></select>
</td>
</tr>
</table>
</div>
</fieldset>
Javascript functions used
function SelectMoveRows_all(SS1, SS2) {
var SelID = '';
var SelText = '';
// Move rows from SS1 to SS2 from bottom to top
for (i = SS1.options.length - 1; i >= 0; i--) {
//if (SS1.options[i].selected == true)
{
SelID = SS1.options[i].value;
SelText = SS1.options[i].text;
var newRow = new Option(SelText, SelID);
SS2.options[SS2.length] = newRow;
SS1.options[i] = null;
for (j = SS2.options.length - 1; j >= 0; j--) {
SS2.options[j].selected = true;
}
}
}
SelectSort(SS2);
}
function SelectMoveRows(SS1, SS2) {
var SelID = '';
var SelText = '';
// Move rows from SS1 to SS2 from bottom to top
for (i = SS1.options.length - 1; i >= 0; i--) {
if (SS1.options[i].selected == true) {
SelID = SS1.options[i].value;
SelText = SS1.options[i].text;
var newRow = new Option(SelText, SelID);
SS2.options[SS2.length] = newRow;
SS1.options[i] = null;
for (j = SS2.options.length - 1; j >= 0; j--) {
SS2.options[j].selected = true;
}
}
}
SelectSort(SS2);
}
function SelectSort(SelList) {
var ID = '';
var Text = '';
for (x = 0; x < SelList.length - 1; x++) {
for (y = x + 1; y < SelList.length; y++) {
if (SelList[x].text > SelList[y].text) {
// Swap rows
ID = SelList[x].value;
Text = SelList[x].text;
SelList[x].value = SelList[y].value;
SelList[x].text = SelList[y].text;
SelList[y].value = ID;
SelList[y].text = Text;
}
}
}
}
I want an incremental + option in my script eg. one by one expansion.
Suppose after click on Optiontional Configurations + than Network Config will be expand with another + option, now if I want another input than I will click on + and Neighbor Config will be expand.
Please help me no this, I am new on javascript, thanks in advance.
<html>
<h>OPSF Configuration</h>
</br>
<head>
<script type="text/javascript">
function defaultconf() {
var nodes = document.getElementById("d1").getElementsByTagName('*');
for(var k = 0; k < nodes.length; k++)
{
nodes[k].style.visibility ="hidden";
}
}
function options1() {
var str = arguments[0];
var nodes = document.getElementById(str).getElementsByTagName('input');
for(var i = 0; i < nodes.length; i++)
{
nodes[i].style.visibility ="hidden";
}
var nodes = document.getElementById(str).getElementsByTagName('button');
var name = document.getElementById(str).getElementsByTagName('label');
for(var i = 0; i < nodes.length; i++)
{
if (nodes[i].style.visibility == "hidden" || name[i].style.visibility == "hidden")
{
nodes[i].style.visibility ="visible";
name[i].style.visibility ="visible";
}
else
{
nodes[i].style.visibility ="hidden";
name[i].style.visibility ="hidden";
}
}
}
function options() {
var str = arguments[0];
var nodes = document.getElementById(str).getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++)
{
if (nodes[i].style.visibility == "hidden")
nodes[i].style.visibility = "visible";
else
nodes[i].style.visibility ="hidden";
}
}
</script>
</head>
<link href="style.css" rel="stylesheet" type="text/css" />
<body onload="defaultconf()">
<br/>
<input type="button" value="+" onclick="options('d1')">Optiontional Configurations </td></tr>
<div id="d1">
<table>
<br/>
<tr><td>
<input type="button" value="+" onclick="options('network')">Network Config
<div id="network">
<table>
<tr>
<td class="style11" valign=top style="height: 4px">Network</td>
<td class="style9" style="height: 4px">
<input type="text" value="<?php echo $network?>" name="network" size="2" style="width: 147px">
</td>
</tr>
</table>
</div>
</td></tr>
<tr><td>
<br/>
<input type="button" value="+" onclick="options('neighbor')">Neighbor Config
<div id="neighbor">
<table>
<tr>
<td class="style11" valign=top style="height: 4px">Neighbor IP</td>
<td class="style9" style="height: 4px">
<input type="text" value="<?php echo $neighbor?>" name="neighbor" size="2" style="width: 147px">
</td>
</tr>
</table>
</div>
</td></tr>
</table>
</div>
</body>
</html>
Simple solution in jquery would be to use .toggle() to toggle the sub-views.
Also I have updated the DOM structure.
jQuery Code:
$(function() {
var siblingCounter = 0;
$('.sub-view').hide();
$('.main-view').on('click', function() {
var localCounter = $(this).hasClass('default') ? siblingCounter++ : 0;
$(this).siblings('.sub-view').eq(localCounter).toggle();
});
});
Live Demo # JSFiddle
Note:
If you are using jQuery library then avoid writing code in vanilla javascript unless you need something which is not available in jQuery [I personally havent come across so far ].
Use a class selector for applying generic/common css styles rather than creating seperate id selector styles. basically this will prevent redundant css styles across multiple rule-set
I have a checkbox list of items. I want everytime I check items, to be able to display the price of the item and the sales tax for it, sum a subtotal of each value (price and tax) and sum the total cost. This is what I've done so far (the code is a mix from scripts I' ve found online):
<html>
<head>
<title>List</title>
<SCRIPT>
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'item'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value);
}
}
document.getElementById('totalcost').value = sum.toFixed(2);
}
</SCRIPT>
</head>
<body>
<FORM >
<table border="1px" align="center">
<tr>
<td>List of Items
<td>Price
<td>Tax
</tr>
<tr>
<td><input type="checkbox" id='item1' value="10.00" onclick="UpdateCost()">item1
<td><INPUT TYPE="text" id='price1' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax1' SIZE=5 value="">
</tr>
<tr>
<td><input type="checkbox" id='item2' value="15.00" onclick="UpdateCost()">item2
<td><INPUT TYPE="text" id='price2' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax2' SIZE=5 value="">
</tr>
<TR>
<TD>Subtotals
<TD><INPUT TYPE="text" id="subtotal1" value="" SIZE=5>
<TD><INPUT TYPE="text" id="subtotal2" value="" SIZE=5>
</TR>
<tr>
<td>Total Cost:
<td><input type="text" id="totalcost" value="" SIZE=5>
<td><input type="reset" value="Reset">
</tr>
</table>
</FORM>
</body>
</html>
Here is a working implementation using Knockout.js. The fiddle is here: http://jsfiddle.net/pJ5Z7/.
The ViewModel and Item functions define your data structure and logic. Bindings to properties in the view-model are done in the HTML and Knockout will update those dynamically. These are two-way: I left the price values as inputs to illustrate this. If you check an item and change its price, you will see that change reflected in the rest of the model and view (after the input loses focus).
This approach allows for clean separation of concerns and much more maintainable code. Declarative bindings in Knockout and similar libraries help you avoid manual DOM manipulation as well.
If you want to change your dataset, all you have to do is add or remove items in the initialization code:
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
With the old approach, you would have had to update the DOM as well as all of your logic. This data could even be loaded dynamically from a web service or anywhere else.
I also cleaned up the markup a bit and moved the size definition of input elements to CSS. It's better practice to define styles there.
If you want to learn more, just go to the Knockout website. There are a number of helpful demonstrations and tutorials.
JavaScript
//Main viewModel
function ViewModel(items) {
var self = this;
self.items = ko.observableArray(items);
self.priceSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].price()));
}
return sum.toFixed(2);
});
self.taxSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].taxAmount()));
}
return sum.toFixed(2);
});
self.totalCost = ko.computed(function() {
return (parseFloat(self.priceSubtotal()) + parseFloat(self.taxSubtotal())).toFixed(2);
});
//Functions
self.reset = function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
items[i].selected(false);
}
};
}
//Individual items
function Item(name, price) {
var self = this;
self.name = ko.observable(name);
self.price = ko.observable(price);
self.selected = ko.observable(false);
self.taxRate = ko.observable(0.06);
self.taxAmount = ko.computed(function() {
return (self.price() * self.taxRate()).toFixed(2);
});
}
//Initialization with data- this could come from anywhere
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
//Apply the bindings
ko.applyBindings(new ViewModel(items));
HTML
<form>
<table border="1px" align="center">
<tr>
<td>List of Items</td>
<td>Price</td>
<td>Tax</td>
</tr>
<!-- ko foreach: items -->
<tr>
<td>
<input type="checkbox" data-bind="checked: selected" />
<span data-bind="text: name"></span>
</td>
<td>
<input type="text" data-bind="value: price"/>
</td>
<td>
<span data-bind="text: selected() ? taxAmount() : ''"></span>
</td>
</tr>
<!-- /ko -->
<tr>
<td>Subtotals</td>
<td>
<span data-bind="text: priceSubtotal"></span>
</td>
<td>
<span data-bind="text: taxSubtotal"></span>
</td>
</tr>
<tr>
<td>Total Cost:</td>
<td>
<span data-bind="text: totalCost"></span>
</td>
<td>
<input type="button" value="Reset" data-bind="click: reset" />
</td>
</tr>
</table>
</form>
So I have this table:
<table border="1" align="center">
<tr>
<td>Broj_pu</td>
<td>Naziv_pu</td>
<td>ID</td>
<td>Naselje</td>
<td>zupanija</td>
</tr>
<tr>
<td><input type="text" ID="broj_pu" onkeydown="Filter(document.getElementById('broj_pu').value, 'broj_pu')" /></td>
<td><input type="text" ID="naziv_pu" onkeydown="Filter(document.getElementById('naziv_pu').value, 'naziv_pu')" /></td>
<td><input type="text" ID="ID" onkeydown="Filter(document.getElementById('ID').value, 'ID')" /></td>
<td><input type="text" ID="naselje" onkeydown="Filter(document.getElementById('naselje').value, 'naselje')" /></td>
<td><input type="text" ID="zupanija" onkeydown="Filter(document.getElementById('zupanija').value, 'zupanija')" /></td>
</tr>
<tr class="row" ID="row_filter">
<td>10000</td>
<td>Zagreb</td>
<td>1</td>
<td>Sljeme</td>
<td>ZAGREBACKA</td>
</tr>
<tr class="row" ID="row_filter">
<td>10000</td>
<td>Zagreb</td>
<td>2</td>
<td>Zagreb-dio</td>
<td>ZAGREBACKA</td>
</tr>
<!-- A lot of rows -->
...
</table>
And also I have started this JavaScript:
<script type="text/javascript">
function Filter(text, column_name){
var x = document.getElementByClassName("row");
var i = 0;
var y;
if (text != ""){
switch (column_name){
case "broj_pu":
for (i = 0; i < x.length; i++){
y = x[i].getElementByTagName("td");
if((y[0].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "naziv_pu":
y = x[i].getElementByTagName("td");
if((y[1].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "ID":
y = x[i].getElementByTagName("td");
if((y[2].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "naselje":
y = x[i].getElementByTagName("td");
if((y[3].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "zupanija":
y = x[i].getElementByTagName("td");
if((y[4].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
}
}
}
</script>
Now, I need to filter the table as the user inputs letters to the text fields, but I have no idea how to edit the display document as I enter the data.
Anyone have an idea?
EDIT1:
So I edited the script but it doesn't seem to work. What did I do wrong?
This question is reminding me of how java script is nasty without any framework support :)
However I have sorted-out this issue for you ( tested on firefox 10.0.2).
check the complete working solution on jsfiddle
please remember this is just working example , you might need to write ALL-Browser compliant script .
script:
var filters=['hide_broj_pu','hide_naziv_pu','hide_ID','hide_naselje','hide_zupanija'];
function ExcludeRows(cls){
var skipRows=[];
for(i=0;i<filters.length;i++)
if(filters[i]!=cls) skipRows.push(filters[i]);
var pattern=skipRows.join('|')
return pattern;
}
function Filter(srcField){
var node=srcField.parentNode;
var index=srcField.parentNode.cellIndex;
//all the DATA rows
var dataRows= document.getElementsByClassName("row");
//ensure that dataRows do not have any filter class added already
var kids= dataRows.length;
var filter ='hide_'+srcField.id;
var pattern = ExcludeRows(filter);
var skipRow = new RegExp(pattern,"gi");
var searchReg =new RegExp('^'+srcField.value,'gi');
var replaceCls= new RegExp(filter,'gi');
for(i=0; i< kids ; i++){
//skip if already filter applied
if(dataRows[i].className.match(skipRow)) continue;
//now we know which column to search
//remove current filter
dataRows[i].className=dataRows[i].className.replace(replaceCls,'');
if(!dataRows[i].cells[index].innerHTML.trim().match(searchReg))
dataRows[i].className=dataRows[i].className +' '+ filter;
}
}
HTML
<table border="1" align="center">
<tr><td>Broj_pu</td><td>Naziv_pu</td><td>ID</td><td>Naselje</td><td>zupanija</td></tr>
<tr>
<td><input type="text" ID="broj_pu" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="naziv_pu" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="ID" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="naselje" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="zupanija" onkeydown="Filter(this)" /></td>
</tr>
<tr class="row" ><td>10000</td><td>Zagreb</td><td>1</td><td>Sljeme</td><td>ZAGREBACKA</td></tr>
<tr class="row" ><td>10000</td><td>Zagreb</td><td>2</td><td>Zagreb-dio</td><td>ZAGREBACKA</td></tr>
</table>
CSS
.hide_broj_pu,
.hide_naziv_pu,
.hide_ID,
.hide_naselje,
.hide_zupanija
{display:none}
For Javascript Table Search, Try:
<p>Search: <input type="text" id="searchTerm" onkeyup="doSearch()" /></p>
<table id="dataTable">
<script>
function doSearch() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("searchTerm");
filter = input.value.toUpperCase();
table = document.getElementById("dataTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
</script>