How to can i display a value of a selected button? - javascript

The following code creates a Buttons, with CSS when one of the button is clicked it changes color, each button created has its own value.
So i want to display a VALUE of a selected button if clicked on my HTML page how can manage that?
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input '
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\'toggle(this);' + onClick + '\'' : '')
+ '>';
}
function toggle(ths) {
$(ths).toggleClass("btnColor");
$("#tb").toggleClass("btnColorR");
}
function DisplayButtons(cableData) {
var newContent = '';
$.each(cableData,
function (i, item) {
newContent += createButtons("tb" + item.CommonCable, null, "submit", item.CommonCable,toggle);
});
$("#Categories").html(newContent);
}

$(ths).val() or $(ths).attr('val') will get you the value.
Demo

Related

give multiple params for a tag onclick function in JSP

I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .

How do you pass json data from one page to another to reference the same row of data?

I am pulling address location information from a google spreadsheet and using it to create buttons. When you click on a button it then should open and populate the data for that location in a new page or if need into a dialog box.
How do you pass the information to a new page and complete the if statement? Everything works great if I manually add the entry.id.$t string in the last if statement.
$(document).ready(function () {
$(function FISLocations() {
$.getJSON("https://spreadsheets.google.com/feeds/list/GoogleSpreadsheetKey/od6/public/values? alt=json-in-script&callback=?",
function (data) {
$('.loc').append('<ul class="collapsibleList" id="list"><li><label for="mylist-node1" class="css_btn_classlist">Alabama</label><input type="checkbox" id="mylist-node1" /><ul class="loclist"></ul></li></ul>');
$.each(data.feed.entry, function (i, entry) {
var item = '<span style="display:none ">' + entry.id.$t + '</span>';
item += ' ' + entry.gsx$cityst.$t;
if (entry.gsx$state.$t == "AL") {
$('.loclist').append('<li>' + item + '</li>');
};
});
$('.poploc').append('<div class="items"></div>');
$.each(data.feed.entry, function (i, entry) {
var itemp = '<span style="display:none ">' + entry.id.$t + '</span>';
itemp += '' + entry.gsx$address1.$t + '<br/>';
itemp += ' ' + entry.gsx$city.$t + ', ';
itemp += ' ' + entry.gsx$state.$t;
itemp += ' ' + entry.gsx$postal.$t + '<br/>';
itemp += ' ' + entry.gsx$phone.$t + '<br/>';
itemp += ' ' + entry.gsx$fax.$t + '<br/>';
itemp += '<div class="px12bold"> ' + entry.gsx$email.$t + '<br/ ></div>';
itemp += '<div class="locmid"><br/><a ' + entry.gsx$androidloc.$t + 'class="css_btn_classsmall noselect">Map Us</a>';
itemp += ' Email Us ';
itemp += ' Call us </div>';
if (entry.id.$t == ? ? ? ? ? ? ) {
$('.items').append('<br>' + itemp + '</span><br/>');
};
});
});
});
});

Displaying a class name

Hi guys i have a Javascript code here which creates HTML buttons onload with the buttons attributes being fetched from the database through an ASP page. Now i want to display these attributes, i can display the id, type and value but the class shows as undefined. i went to the page on the browser and inspected the element and the class is shown, but not on the alert box. Please help...
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input'
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\''+ onClick + '\'':'')
+ '>';
}
function DisplayButtons(cableData) {
var newContent = '';
$.each(cableData, function (i, item) {
newContent += createButtons(
item.CommonCable,
"unclickedButton",
"submit",
item.CommonCable,
'alert(this.id + " " + this.class + " "+"clicked")'
);
});
$('#Categories').html(newContent);
}
change this.class to this.className..
When you get to the alert parameter, pass in this:
'alert(this.id + " " +' + $(this).attr(class) + ' + " "+"clicked")'
You can use jQuery to get the class name.

How to change background -color when toggle button clicked?

I need help :
i've got a problem when clicking any toggle button i want it to change background-color and when clicked again it must return to original background-color .
your help will be highly appreciated.
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input '
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\'' + onClick + '\'' : '')
+ '>';
}
function DisplayButtons(cableData) {
var newContent = '';
$.each(cableData,
function (i, item) {
function toggle() {
$(this).clicked ? $("#tb").addClass("btnColor") : $(this).removeClass("btnColor");
$("#tb").toggleClass("btnColorR");
}
newContent += createButtons("tb" + item.CommonCable, null, "submit", item.CommonCable,
' alert("clicked")');
});
$("#Categories").html(newContent);
}
You'll need a click event listener on your button. Whenever the button is clicked, the toggleClass() will switch between the class normal and active, each containing a different background color.
Based on your comments, it appears you're creating these buttons dynamically from values in a database, so you won't know the id of the button beforehand. For this situation, instead of creating a click event listener for a specific button (referencing the id), create the event for all buttons on your page $('input[type=button]').click(function () {....
HTML:
<!--
These buttons were generated dynamically from values stored in a database
I won't know their ids
-->
<input type="button" name="btn_1_from_db" value="Toggle Color1" />
<input type="button" name="btn_2_from_db" value="Toggle Color2" />
<input type="button" name="btn_3_from_db" value="Toggle Color3" />
<input type="button" name="btn_4_from_db" value="Toggle Color4" />
<div id="target" class="normal">
My color will change
</div>
CSS
.normal {
background-color: green;
}
.active {
background-color: red;
}
Javascript:
$(document).ready(function () {
// If any button is clicked, toggle its assigned class (changes the color)
$('input[type=button]').click(function () {
$('#target').toggleClass('active');
});
});
Example: http://jsfiddle.net/EkAAh/
Try your code like
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input '
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\'toggle(this);' + onClick + '\'' : '')
+ '>';
}
function toggle(ths) {
$(ths).toggleClass("btnColor");
$("#tb").toggleClass("btnColorR");
}
function DisplayButtons(cableData) {
var newContent = '';
$.each(cableData,
function (i, item) {
newContent += createButtons("tb" + item.CommonCable, null, "submit", item.CommonCable,
' alert("clicked")');
});
$("#Categories").html(newContent);
}

Shorten a method. Syntax better practices

I've been learning via jQuery how to shorten things up. I was wondering if this script can be expressed in a less verbose way? I don't like how everything sits on one huge line.
items.push('<li id="' + key + '">' + ' (key: ' + key + ')(value: ' + val.value + ')(type: ' + val.type + ') (range: ' + val.range + ') (clone: ' + val.clone + ') (archive: ' + val.archive + ') (access: ' + val.access + ')</li>')
Assuming that the object will always have the correct key/values:
str = '';
for (var item in val) {
str += '(' + item + ': ' + val[item] + ')';
}
$("<li>").attr('id', key).text(' (key: ' + key + ')' + str);
http://jsfiddle.net/36Nyu/
If items is another element, you can do something like this.
var str;
for(var i in val)
str += '('+ i +': '+ val[i] +')';
$('<li>', {
id: key,
text: str
}).appendTo(items);
You could use jquery tmpl, or similar:
var template = '(key: ' + key + ')(value: {{value}})(type: {{type}}) (range: {{range}}) (clone: {{clone}}) (archive: {{archive}}) (access: {{access}})';
$('<li />').attr('id', key).html($.tmpl(template, val));
Or, use a string.Format equivalent:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
/* Allow escaping of curly brackets with {{ or }} */
if (m === '{{') { return '{'; } else if (m === '}}') { return '}'; }
return typeof args[n] != 'undefined' ? args[n] : '{' + n + '}';
});
};
var text = '(key: {0})(value: {1})(type: {2}) (range: {3}) (clone: {4}) (archive: {5}) (access: {6})'.format(key, val.type, val.range, val.clone, val.archive, val.access);
Assuming you're appending all of the key/value pairs in the val object, doing something like this would be pretty maintainable:
var liPrefix = '<li id="' + key + '">(key: ' + key + ')',
liSuffix = '</li>',
liData = '';
$.each(val, function(k, v) {
liData += ' (' + k + ': ' + v + ')';
});
items.push(liPrefix + liData + liSuffix);
See demo

Categories

Resources