I have a div containing a group of divs.
I want the divs inside to work as links that move to another page after saving this link's value.
The div consists of the id in the div attribute, & the name in the div's value as follows:
Html:
<div id="ClasssesList" ></div>
jQuery:
function GetClassesList(data) {
var classes = (typeof data) == 'string' ? eval('(' + data + ')') : data;
$('#ClasssesList').empty();
for (var i = 0; i < classes.length; i++) {
var text = '<button class="BigDiv" value="' + classes[i].Cls_ID + '" >' + classes[i].Cls_Name + '</button>';
$('#ClasssesList').append(text);
}
}
I want to save the value of the clicked id in a localStorage then move to the next page:
I tried to make it as follows, but it doesn't seem to be working:
$("#ClasssesList").bind('click', 'button.BigDiv',CallLink());
function CallLink(e) {
localStorage['ClassID'] = $('Button.BigDiv').attr('value');
window.location.replace("Teacher_Attendance.htm");
}
Do you know what should I do to let it work ?
function CallLink(e) {
localStorage.setItem('ClassID', $('Button.BigDiv').attr('value'));
window.location.replace("Teacher_Attendance.htm");
}
And to get that item try:
localStorage.getItem('classID');
Format to set data to localStorage is
localStorage.setItem(key, value);
here value is string format;
you will get more here Microsoft, Mozilla and Apple.
And one note
I think your bind function
$("#ClasssesList").bind('click', 'button.BigDiv',CallLink())
should be written as
$("#ClasssesList").on('click', 'button.BigDiv',CallLink())
Related
Im trying to create a simple function that create span's with an class that equals whatever is piped into the function. These spans fill inside a parent div. I also want to ensure that once a span has been added that another span is not add with that id/class, unless my multiSearchEnabled boolean is true.
Here is some code i've
function createBadge(badge_type) {
var badge_parent_div = $("#badge-column-div");
var badge = "<span class='badge-text " + badge_type + "'>" + badge_type + "</span>";
if (!$(badge_parent_div.find("span").hasClass(badge_type))) {
badge_parent_div.append(badge);
} else {
if (multiSearchEnabled) {
badge_parent_div.append(badge); // Add another Badge, since search contains multiples
}
}
}
However this doesnt seem to work, this function will be ran onKeyUp therefore is why i need to detect if the span already exists for this type, so i dont duplicate it.
Updated based on suggestions
function createBadge(badge_type) {
var badge = "<span class='" + badge_type + "'>" + badge_type + "</span>";
var bHasBadge = $("#badge-column-div").has('.' + badge_type);
if (bHasBadge == false || (bHasBadge && multiSearchEnabled == true))
{
// add it
$("#badge-column-div").append(badge);
}
}
However with the following code, nothing ever get's added. I need it add a badge initially, then only if the multiSearchEnabled boolean is true to add more than one.
has() checks for child controls matching a selector.
function createBadge(sBadgeType)
{
var oBadgeParent = $("#badge-column-div");
var bHasBadge = oBadgeParent.has("span." + sBadgeType)
if (bHasBadge == false || bMultiSearchEnabled)
oBadgeParent.append
(
$("<span class='badge-text " +sBadgeType+ "'>" +sBadgeType+ "</span>")
);
}
I have a dropdown whose options get filled dynamically:
function populateDropdown(dropdownNum) {
// invokeWebService uses $.ajax
json = invokeWebService("GET", "/webservice/dropwdownOptions");
optionsHtml = "";
$.each(json, function(count, jsObj) {
optionValue = jsObj.name
optionsHtml+="<option>" + optionValue + "</option>";
});
var dropdownId = "#NRdropdown_" + dropdownNum;
$(dropdownId).html(optionsHtml);
}
function display(blockNum) {
var url = "/webservice/blocks" + blockNum;
var response = invokeWebService("GET", url);
var replacementHtml = "";
var currBlock = "blah";
$.each(response, function(i, block) {
currName = block.name;
var textfield = "<input type='text' id='blockValue" + block.id +
"'>";
var dropdownMenu = "<select id=\"NRdropdown_" + i +
"\"onClick=\"populateDropDown(" + i +
")\"><option>Existing Blocks</option>"
var submitButton = "<input type='submit' value='UPDATE' id='" +
block.id + "'><br><br>";
replacementHtml = currName + textfield + dropdownMenu + submitButton;
});
$("#main").html(replacementHtml);
}
The javascript function "populateDropdown(dropdownNum)":
Makes the ajax request
Parses the json response for the option values into an html string called optionsHtml
Replaces the inner html of the select element with the option values via:
var dropdownSelector = "#NRdropdown_" + dropdownNum;
$(dropdownSelector).html(optionsHtml)
1) When I click on the dropdown arrow, I STILL see "Existing Blocks".
2) After 1 sec I see the first dynamically generated option UNDERNEATH the "Existing Blocks" option, I don't see the other dynamically generated options.
3) Then I click outside the dropdown and see the dropdwon showing the first dynamically generated value.
4) Finally I click the dropdown arrow again and it works as it should with all the dynamically generated values.
How do I make it work so that:
When the page first loads, the dropdown shows "Existing Blocks".
Once I click the dropdown arrow, the dropdown should show all dynamically generated values without the "Existing Blocks" value.
Thanks!
the dropdown listener should be for onmousedown, not onclick
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
im currently working on a simple todo list. I store the tasks in cookies and when the web page reloads i retrieve my previous tasks from the cookies. However i cannot save there my tasks as completed, i.e. the tasks that i marked as complete.
function toHTML(id, text) {
return '<div class="todo" id="' + id + '">' +
'<div id="' + cbid + '"><input type="checkbox" class="check_todo" name="check_todo"/></div>' +
'<div class="todo_description" contentEditable = "true">' +
text +
'</div>' +
'<img src = "sun-icon.gif" class="close" title = "Delete the Task" />' +
'</div>';
}
When i press checkbox the div with class = "todo" gets class = "checked" and the text (todo_description) inside this div becomes crossed, also the div with class="todo" itself gets another color.
$('#item-' + counter +' .check_todo').unbind('click');
$('#item-' + counter +' .check_todo').click( function() {
var todo = $(this).parent().parent();
todo.toggleClass('checked');
});
When i reload the page i see my previous tasks but not completed tasks, because i retrieve from cookies only text:
function get_cookies_array(){
var cookies = { };
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
//here i display my tasks
var cookies = get_cookies_array();
var i = 0;
for(var name in cookies) {
$('.todo_list').prepend(toHTML('item-' + (i++), cookies[name]));
}
I tried to check for the class "checked" like
if $(cookies[name]).hasClass('checked')
{ make stylings for this div}
but this doesnt work, i need to check for div with class = "todo" which becomes "todo checked" when i press checkbox.
I'd appriciate if someone could help me!
if you want to check if checkbox is checked you can try :
$('#id_checkbox').is(':checked');
if you want to get your cookie without reloading your page you can setTimeout between the set and the get of cookiees
As the title says, I'm trying to set the value of a .clone()'d form field using the results of a $.getJSON() request. All of the return values have the same key as the name attribute of the form field they belong to.
Naturally, I tried to use .val("foo") to deal with cross-browser/field type discrepancies but it wouldn't work. Oddly, .attr("value","foo") does.
Any ideas? Is this expected behavior, or an undocumented quirk? Here is the relevant code snippet:
function showSites(){
$.getJSON("process.php?action=showSites", function(data) {
var items = [];
$.each(data.sites, function(key, val) {
var $form = $("#addSiteForm").clone();
var buttons = '<button id="getCert" class="button" href="getCert.php?id=' + val.id + '">Get Cert</button>'
+ '<button id="updateSite" class="button" href="process.php?action=updateSite&id=' + val.id + '">Update Site</button>'
+ '<button id="deleteSite" class="button" href="process.php?action=deleteSite&id=' + val.id + '">Delete Site</button>';
// set siteId
$form.find("input[name=siteId]").attr("value",val.id);
// change values
$.each(val, function(i,v){
$form.find("[name="+i+"]").val(v);
});
items.push('<h3>' + val.name + '</h3>');
items.push("<div class='site'>");
items.push("<form class='siteForm' id='"+val.id+"'>");
items.push($form.html());
items.push("</form>");
items.push(buttons);
items.push("</div>");
});
var foo = items.join('');
$("#sites").prepend(foo).accordion("destroy").accordion();
});
});
You can use .val() property in input tags( text box, textarea,..) only.
attr("attrname","value") this is used to set value to any tags. You can set some dummy attr in div tag and retrieve value attr("attrname");