Input button stop working when filling the div - javascript

I have a div in my html defined like this:
<div id="rgroups" class="dialogWindow fileDialog" style="display:none;" >
<input id="rgroups_ok" class="dialogButton" type="submit" value="Done"/>
<label for="rgroups_ok"><span class="label">Start</span></label>';
</div>
In my js file the rgroups_ok is define that way:
$('rgroups_ok').observe('click', function ()
{
ui.hideDialog('rgroups');
});
If I keep to that it's working fine, the button is working.
Then I am filling that html div like that:
var div=document.getElementById('rgroups');
div.style.display='inline-block';
for (i = 1; i <= count; i++) {
div.innerHTML+=' Rgroup '+i+' values separated by / symbol: \n <textarea id="Rgroup"'+i+' rows="4" cols="50"> </textarea>';}
With that inner HTML defines button stops working...
Any clue?
Thanks

Try changing observe to on
so this:
$('#rgroups_ok').on('click', function ()
{
ui.hideDialog('rgroups');
});
You can check the details for on() here.
Observe seems to be obsolete and may not be a thing you are looking for.

I could not understand clearly. so I made demo code.
If you could mention your main subject/idea it would help us.
Full code:
Head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Body:
<div id="rgroups" class="dialogWindow fileDialog">
<label for="rgroups_ok">
<span class="label">Start</span>
</label>
</div>
<div id="rgroups2" style="display:none;">
<p onclick="textA()">Hey click here</p>
</div>
<button id="rgroups_ok2" class="dialogButton" onclick="a()">
Done
</button>
<script>
function a() {
$('#rgroups').css("display", "none");
$("#rgroups2").css("display", "inline-block");
$("#rgroups_ok2").css("display", "none");
};
function textA() {
var count = 100;
//document.getElementById("rgroups2").innerHTML += "Bye";
for (i = 1; i <= count; i++) {
document.getElementById("rgroups2").innerHTML += '<p> Rgroup ' + i + ' values separated by / symbol: \n <textarea id="Rgroup" rows="4" cols="50">' + i + ' </textarea></p>';
}
}
</script>

Hi found the solution on this post:
Is it possible to append to innerHTML without destroying descendants' event listeners?
To sum up it's not possible to append without destroying all child. Ths the event have to be reconstructed.
Thanks

Related

How to identify a div id and trigger it

I got a problem with one of the sites with JavaScript, and I need to automate a click and then find out how many turns I got before I run out of them. As in, for example, let's say I have 8 turns. So what I would need is to automatically have JavaScript to trigger said div id, 8 times. (As in, I add like this)
Link:https://jsfiddle.net/yxsgp8tc/
<body>
<button id="test">Test</button>
<p>
On box should be number of tests
</p>
<form>
<label><input type="text"/>00-99</label>
<button>
trigger it
</button>
</form>
</body>
in plain javascript, you would target unique elements (using an id) by using document.getElementById('<element_id'). If you wanted to target a class, you would document.querySelector('.<class_name>') for the first instance of the class, or document.querySeletorAll('.<class_name>')
Also, your input tag was misspelled "imput", and is a singleton tag so you don't have to close it off.
Assuming you wanted a way to trigger a click event, here's a basic example:
<head>
<script>
const test = document.getElementById('test');
const trigger = document.getElementById('trigger')''
test.addEventListener('click', () => {
const num_test = document.getElementById('num_tests').value;
for (let i = 0; i < num_test; i++) {
trigger.click();
}
});
trigger.addEventListener('click', () => {
console.log('trigger clicked');
});
</script>
</head>
<body>
<button id="test">Test</button>
<p>
On box should be number of tests
</p>
<form>
<input type="text" id="num_tests" value="">
<button id="trigger">
trigger it
</button>
</form>
</body>
https://jsfiddle.net/qr1z3d6e/2/
first in the jsfiddle.net link there are some errors such as imput instead of input.
I haven't tested it, but if I understand correctly is it something like this? try it.
<body>
<input id="myinput" type="text">00-99</input>
<button id="clickme">
</body>
<script>
var button = document.getElementById("clickme"),
count = 99;
var myInput = document.getElementById("myinput")
button.onclick = function(count){
count -= 1;
myInput.innerHTML = "00 " + count;
};
</script>

jquery : how to toggle div after using search function on it?

I'm using a search function to highlight text (function 2) in different chapters. In parallel most of this text is stored in div called content to ease reading. You can toggle these div to read the text (function 1).
When text is found by function 2, it's no longer possible to toggle the text in this chapter. I suppose this is related to use of "this" in function 1 (If I delete this it works) or handlers (if I add live in front of click in function 1 it works but live is deprecated and remplacement "on" is not working).
// function 1 : toggle content when clicking the button
$(".chapter button").on('click',function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
console.log(id)
$('#' + id + '+*').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
console.log(str);
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
// but i want to highlight all occurences of the word in this chapter ? how can I define index d ?
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
$(this).html($(this).html().replace(strCut[i], '<font color="red">$&</font>'));
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
The problem was your $(this).html(). The .replace that you did removes the event listener of your button, because it modifies the DOM. Instead of getting the whole .html(), I did it with .children(), and then replaced just the text of it.
About replacing all the occurrences of the chapter word, you could use a Regular Expression. Using a string will replace just the first occurrence of the string. With the regular expression you can replace all of them.
// function 1 : toggle content when clicking the button
$(".chapter button").click(function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
$('#' + id + '+*').closest('.content').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
var regex = new RegExp(strCut[i],"g")
$(this).children().each(function (index,element) {
const text = $(element).html().replace(regex,'<font color="red">$&</font>')
$(element).html(text)
})
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1 and the second ocurrence of chapter also highlighted
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
EDIT
I wasn't clear enough about the errors, sorry, and I've noticed the right solution.
The point is that, instead of modifying the parent element, I've changed the text of the childrens. When you change the whole html, you remove the listener of your buttons when you add it again to the html, and that's why isn't possible to toggle the divs.

Javascript - Repeated use of a function without it removing previous instances?

How would I repeat the output of a function, without it affecting previous instances outputs of the function?
For some context:
I am creating a text editor and have created a "link-maker" which creates an relative href link.
However, when I append the link to the text area content, the link displays perfectly for the first instance. Yet, if I repeat that function to add another relative link, it removes the html wrapping the first link appended.
I have tried changing the text output of the link to getElementByClassName, as I thought that the ID would only be best used for a sole function which would not need to be repeated. Where as by using the class it allows for more general use.
Some code for example:
<textarea name="textarea" class="txtarea" id="textarea" style="display: none; font-family: Arial;"></textarea>
<iframe name="editor" id="editor" style="width:824; height: 400; font-family: Arial;"></iframe>
function bcmllink() {
var logicalid = document.getElementById("logicalid");
var txtinput = document.getElementById("txtinput");
var txtOutput = document.getElementById("txtOutput");
var name = logicalid.value;
txtOutput.value = "\x3ca href\x3d\x22\x23\x22 bcmltype\x3d\x22link\x22 logicalid\x3d\x22" + logicalid.value + "\x22\x3e" + txtinput.value + "\x3c\x2fa\x3e"
}
function appendtotext() {
var myTextArea = $('.txtarea');
myTextArea.val(editor.document.getElementsByTagName('body')[0].innerHTML = editor.document.getElementsByTagName('body')[0].
textContent + txtOutput.value + " ")
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<textarea name="textarea" class="txtarea" id="textarea" style="display: none; font-family: Arial;"></textarea>
<iframe name="editor" id="editor" style="width:824; height: 400; font-family: Arial;"></iframe>
<div id="bcml">
<h3>BCML Links</h3>
<form action="">
<fieldset class="bcml_links">
<label>Enter your logical id</label><input type="number" id="logicalid" class="left5"/><br><br>
<label>Enter your text</label><input type="text" id="txtinput" class="left5"/><input class="left5" type="button" value="Generate" onClick="bcmllink()" /><br><br>
<input type="text" style="width : 600;" id="txtOutput" /><br><br>
<b>Copy and paste this text into your source view</b>
<input type="button" value="append" onClick="appendtotext()"/>
</fieldset>
</form>
Maybe you should consider using lists instead of textarea. Im currently using this for a chatapp im creating and it doesnt remove the previous messages when i recieve a new one.
You are already importing jquery. Why not make use of its .text() function?
$('textarea#textarea').text("<a href='ok'>Click here</a>");
Note, that you will not have to worry about formatting HTML or escaping characters.
If you want to append to a previously filled textarea: you would do something like:
var old_text = $('textarea#textarea').text();
$('textarea#textarea').text(old_text + "<a href='ok'>Click here</a>");
I managed to find the answer to what I was looking for:
function appendtotext() {
var myTextArea = $('.txtarea');myTextArea.val(editor.document.getElementsByTagName('body')[0].innerHTML = editor.document.getElementsByTagName('body')[0].
innerHTML + txtOutput.value + " ")}
The issue was that I was previously using textContent on the last line (where innerHTML now sits). This meant that with each instance of the function being used, it was removing the surrounding html tags and placing in only the text content.
See here for further information:
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

access the exact view in a raw using js

My view has a button and the view is looped.so it has raws.
when i click the button of a single raw i need to color that button.
so i added a onclick="select_Button(<?php echo $rawID?>)" to the raw's button in my view
select_Button is my funtion in js
function select_Button(rawNumberOfVote) {
var RawNumber = rawNumberOfVote;
alert ("Form submitted successfully" + RawNumber);
var upVote = document.getElementById("up_vote");
upVote.style.background = "green";
}
like above i send the rawID to the funtion.
how can i edit this line to accept the view called up_vote in that particular raw id that i got from parameter.
var upVote = document.getElementById("up_vote");
becuz if i only use this line it will color the first raw's button instead the one i wanted
Thank you
you can use data attribute in your html referencing to this page and this page. and retraive with this this jquery code snippet:
$("[data-test ='my value']")
or this code snnipet in javascript:
document.querySelectorAll(".example").find(function(dom){
return dom.dataset.test == "expected-value"
});
Update:
accourding to this page querySelectorAll return nodeList and NodeList are not array and we cannot use find method so I change my answer to this code:
<html>
<body>
<div class="post" data-key="1">
<lable>test</lable>
<button type="button" onclick="upvote(1)">up vote</button>
</div>
<div class="post" data-key="2">
<lable>test</lable>
<button type="button" onclick="upvote(2)">up vote</button>
</div>
<div class="post" data-key="3">
<lable>test</lable>
<button type="button" onclick="upvote(3)">up vote</button>
</div>
</body>
</html>
<script type="text/javascript">
var upvote = function(id) {
var nodes = document.querySelectorAll(".post");
console.log(nodes.length);
for(i = 0 ; i < nodes.length ; i++){
console.log(nodes[i].dataset.key);
if (nodes[i].dataset.key == id)
nodes[i].style.backgroundColor = "red";
}
};
</script>

Pass js var into html block being added via appendTo

I've got this html which i'm injecting into the page when someone clicks a button. The html gets appended again each time the button is clicked using the js below.
<div style="display: none;">
<div class="grab-me">
<p>This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
});
});
But what i need to do is where it says "This is fieldset 1" i need to increase that number by 1 each time so subsequent appends say This is fieldset 2, This is fieldset 3 etc etc. I can't see how i can pass a variable (my count var) in to the html block when it gets cloned that will replace that number.
Here is a jsfiddle of it: http://jsfiddle.net/tzbgA/
Any help would be great! Thanks!!
you can give the sentence you want to change class. Then using jQuery selectors change the text inside it.
<body>
<button class="add-member">add more</button>
<div style="display: none;">
<div class="grab-me">
<p class="count">This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
<div id="register">
</div>
</body>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register')
.find('p.count').html('This is fieldset '+count);
count += 1;
});
});
add span:
<p>This is fieldset <span>1</span></p>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
$('.span').html('count');
});
});
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me').clone();
$(grab p).html('This is fieldset '+count).appendTo('#register');
});
});
Fiddle: http://jsfiddle.net/howderek/tzbgA/2/
Here's a version that uses 8 lines of code:
Code (Javascript)
var count = 1,
html = ' <p>This is fieldset #</p><input name="foo[]"/> <input name = "bar[]"/> <input name = "oth[]"/>';
$(function () {
$('.add-member').live("click", function (e) {
e.preventDefault(e);
document.getElementById("register").innerHTML += html.replace("#",++count);
});
});

Categories

Resources