Javascript/Jquery toggle id with multiple variable - javascript

this is my first question, so apologies if not written clearly.
I want to dynamically toggle a comment form after reply button is pressed. There are multiple comments (in below example three) to which a form (with different id) can be rendered separately.
I am able to do this with static id for form but not with dynamically defined id...
I have tried this static approach and this works fine.
var functs_t = {};
functs_t['fun_27'] = $('#reply_comment_id_27').click(function() {$('#form_comment_id_27').toggle('slow');});
functs_t['fun_23'] = $('#reply_comment_id_23').click(function() {$('#form_comment_id_23').toggle('slow');});
functs_t['fun_21'] = $('#reply_comment_id_21').click(function() {$('#form_comment_id_21').toggle('slow');});
However, I am having struggling with a dynamic approach.
var i;
var functs = {};
for (i=0; i<comment_qs_id_list.length; i++) {
var comment_id = comment_qs_id_list[i].toString();
var reply_comment_id = 'reply_comment_id_'+ comment_id;
var form_comment_id = $('#'+reply_comment_id).attr('name');
// works >>> toggles comment 27
functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+'form_comment_id_27').toggle('slow');});
// does not work
//functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+form_comment_id).toggle('slow');});
// works >> toggles everything (but what I want is to hide initially and only toggle after clicking reply button)
//$('#'+form_comment_id).toggle('slow');
};
Thanks so much!

Related

Javascript functions do not work after updating content (Using Document Ready atm.)

I have a question I am working with a form based shopping cart add function and a livesearch (PHP) function where it requests new data with the same classes. I have seen multiple examples besides (document.ready) but none of them seemed to work correctly after the DOM Content has been modified by the PHP livesearch function. (The current method is on the document ready function as you guys can see.
Thanks in advance!
// Icon Click Focus
$('.product').on('click', function() {
var strId = '';
var strId = $(this).attr('class');
var strId2 = strId.replace(' product','');
var strId3 = strId2.replace('product-','');
var formData = "product"+strId3;
document.getElementById("product_toevoeg_id").value = strId3;
var productNaam = $("#"+formData+" .f-productnaam").val();
document.getElementById("productnaam").innerHTML = productNaam;
document.getElementById("product_naam_form").value = productNaam;
var productIngredienten = $("#"+formData+" .f-ingredienten").val();
document.getElementById("ingredienten").innerHTML = productIngredienten;
document.getElementById("ingredienten_form").value = productIngredienten;

Setting a onClick function to a dynamically created button, the function fires onload

I am currently creating a program which utilizes localStorage to create a site with a wishlist like functionality. However when I go to generate the html page that should create the wishlist with the photo of the item, the name and a button to remove said item from the list. But when I go to assign the onClick functionality to the button, the function fires on page load rather then on click. I have four main java script functions, one to add to the localstorage, one to remove from local storage, a helper function for removing and the one that will generate the wishlist page (where the problem is).
function genWishListPage(){
for (var i = 0; i < localStorage.length; i++) {
var item = getWishlist(i);
var name = document.createElement("p");
var removeButton = document.createElement("button");
var image = document.createElement("img")
image.src = item.image;
removeButton.innerText = "Remove from wishlist";
removeButton.onClick = RemoveFromWishList(item.name);
removeButton.setAttribute("ID","remove");
name.innerText = item.name;
document.body.appendChild(image);
document.body.appendChild(name);
document.body.appendChild(removeButton);
document.body.appendChild(document.createElement("BR"));
//removeButton.setAttribute("onclick", RemoveFromWishList(item.name));
//removeButton.addEventListener('click', RemoveFromWishList(item.name));
//document.getElementById("remove").addEventListener("click",RemoveFromWishList(item.name));
}
}
The commented parts are ways I have already tried and gotten the same bug.
Any help or advice is appreciated.
When you write
removeButton.onClick = RemoveFromWishList(item.name); you are assigning the return value of the function call to the onClick event. Instead you can write
removeButton.onClick = function() { RemoveFromWishList(item.name);}
You should assign a function to the onClick event listener.

Creating whole new view based on current user's group sharepoint 2013

I am trying to generate a view based on the current user's group name. Group Name I am gathering from the custom list.
My question is how to apply the gathered group name to 'Group Name' column as a view parameter.
The only solution I figured:
I have created a view with a parameter.
I have added an HTML Form Web Part into the same page and connected it to the list view (sending the value to the parameter via web part connection). Then with a window.onload function I gather the current user's group name and pass this value via Form Postback function. But since the Postback function triggers full page reload, it falls into the endless loop of form submission > page reload.
Another way I have tried is attaching a click event listener to the BY MY GROUPS tab and it works perfectly, but the only disadvantage is that the page reloads each time user clicks on this tab, which I would like to avoid.
So the solution that I need is a way to post the form without a page reload.
Another option suggested here is to use CSR (client side rendering), but that has its own problems:
This code does not work as it is supposed to. In the console it shows me correct items, but the view appears untouchable.
Even if it worked, the other column values are still viewable in the column filter, as in this screenshot:
So, it seems that CSR just hides items from the view (and they are still available). In other words its behavior is different from, for example, a CAML query.
Or am I getting it wrong and there's something wrong with my code?
Below you can find my CSR code:
<script type='text/javascript'>
(function() {
function listPreRender(renderCtx) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var currUserID = _spPageContextInfo.userId;
var cx = new SP.ClientContext('/sites/support');
var list = cx.get_web().get_lists().getByTitle('Group Members');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
cx.load(items, 'Include(_x006e_x50,DepID)');
cx.executeQueryAsync(
function() {
var i = items.get_count();
while (i--) {
var item = items.getItemAtIndex(i);
var userID = item.get_item('_x006e_x50').get_lookupId();
var group = item.get_item('DepID').get_lookupValue();
if (currUserID === userID) {
var rows = renderCtx.ListData.Row;
var customView = [];
var i = rows.length;
while (i--) {
var show = rows[i]['Group_x0020_Name'] === group;
if (show) {
customView.push(rows[i]);
}
}
renderCtx.ListData.Row = customView;
renderCtx.ListData.LastRow = customView.length;
console.log(JSON.stringify(renderCtx.ListData.Row));
break;
}
}
},
function() {
alert('Something went wrong. Please contact developer')
}
);
});
}
function registerListRenderer() {
var context = {};
context.Templates = {};
context.OnPreRender = listPreRender;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
}
ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');
})();
</script>

Createing and calling events in Javascript

I'm working on a choose your own adventure game written entirely in HTML and Javascript; I want to create most of my elements entirely in Javascript to create an awesome dynamic game! I am having trouble using events and event listeners. It's a mystery game; after the player chooses their character from a list, they can invite five guests to a party. One of the guests is killed, leaving you to solve the mystery with three suspects.
After you've selected your player, there's another button that says "Select this character!". When this button is clicked, the player creation UI is supposed to be hidden, and a new UI is visible. With the code as it is now, the "StartGame" function is skipped entirely. What am I doing wrong? Any help you can give would be seriously awesome and greatly appreciated!
btnPlayer = document.createElement('button');
btnPlayer.id = 'BTN_btnPlayer';
btnPlayer.type = 'button';
btnPlayer.addEventListener('click', welcomePlayer(), true);
btnPlayer.onclick = welcomePlayer();
btnPlayer.innerHTML = 'Select This Character!';
myDiv.appendChild(btnPlayer);
EDIT
I modified my button event properties to look like this:
btnPlayer.addEventListener('click', welcomePlayer, true);
//btnPlayer.onclick = welcomePlayer;
One is commented out because neither has worked. I tried clearing my cache, too. Here is my StartGame() function with the button code excluded. I won't include the "charFirstNames[]" and "charLastNames[]" used to create the choices in my dropdownlist. I have them separated in order to tell a more interesting story; they will eventually be database records when I get the bugs and the basics worked out. I don't think I messed up anything up here, but is it possible that I did? The function is called by the only button coded into the HTML.
function startGame(divName) {
myDiv = document.getElementById('story');
lblPlayer = document.createElement('label');
lblPlayer.id = 'LBL_Player';
lblPlayer.htmlFor = 'DDL_PlayerChar';
lblPlayer.innerHTML = 'Please select a character. ';
myDiv.appendChild(lblPlayer);
ddlPlayer = document.createElement('select');
ddlPlayer.id = 'DDL_PlayerChar';
myDiv.appendChild(ddlPlayer);
defOpt = document.createElement("option");
defOpt.value = 0;
defOpt.text = 'Select...';
ddlPlayer.appendChild(defOpt);
//Create and append the options
for (var i = 0; i < charFirstNames.length; i++) {
var option = document.createElement("option");
option.value = charFirstNames[i]+'_'+charLastNames[i];
option.text = charFirstNames[i]+' '+charLastNames[i];
ddlPlayer.appendChild(option);
}
document.getElementById('BTN_Start').hidden = true;
}
The welcomePlayer() function is similar to the startgame() function, creating the interface to invite the first "guest" and removing the player creation UI.
Both of these lines set the onclick handler to the result of calling the welcomePlayer function (see the parens?).
btnPlayer.addEventListener('click', welcomePlayer(), true);
btnPlayer.onclick = welcomePlayer();
You probably mean
btnPlayer.addEventListener('click', welcomePlayer, true);

Differing one button from another on a prototype object jquery

first, the prototype:
function Notification (title, message, id) {
var $title = this.title = title;
var $message = this.message = message;
var $id = this.id = title;
/* ---------------creating HTML prototype */
var $mainDiv = $("<div></div>").appendTo($("#wrapper"));
$mainDiv.attr('id', $id);
$mainDiv.addClass('main-div');
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
$dismissButton.attr('id', 'dismissButton');
var $pTitle = $("<h2></h2>").appendTo($mainDiv);
$pTitle.attr('id', 'title');
$pTitle.text($title);
var $para = $("<p></p>").appendTo($mainDiv);
$para.attr('id', 'message');
$para.text($message);
var $ul = $("<ul></ul>").appendTo($mainDiv);
var $li1 = $("<li></li>").appendTo($ul);
$li1.attr('id', 'okButton');
var $button = $("<button>Ok</button>").appendTo($li1);
$button.addClass('buttons');
/* ---------------Dismissing notifications */
$("#dismissButton").click(function() {
document.getElementById($id).remove();
});
};
So, the prototype is made using new Notification(*arguments here*) and there we get a box with a notification widget. so far so good.
when i press the X button (id dismissbutton) it should remove the box, and it does.
However. if i use the new notification several times i get several boxes (with different ids for the $mainDiv) with their dismiss buttons not working. the upmost widget box's dismiss button is the only one that works, and it deleted all the other boxes as well.
I need to seperate them and have the dismiss button working for each box seperately.
thanks in advance :)
The problem here is that you are creating multiple elements with the same ID (which is invalid HTML by the way).
Every time your run
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
$dismissButton.attr('id', 'dismissButton')
A new "dismiss button" is being created, which has the same ID (dismissButton) with the previous "dismiss buttons" (if any).
The other thing is that every time you run
$("#dismissButton").click(function() {
document.getElementById($id).remove();
});
You instruct only the first "dismiss button" to remove the element identified by the ID $id when clicked.
In my opinion the best way to fix this is by using references to the elements themselves and not IDs.
So I would make the creation of the dismiss button like this;
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
And determine its click callback like this
$dismissButton.on('click', function () {
$mainDiv.remove();
});
This should work fine for you.
Last, but not least I would avoid giving the same ID to any elements, since it produces invalid HTML code. You are doing so in the following lines
$dismissButton.attr('id', 'dismissButton');
$pTitle.attr('id', 'title');
$para.attr('id', 'message');
$li1.attr('id', 'okButton');

Categories

Resources