Get next textarea outside div without id - javascript

I need to get the next textarea, but I'm not being able with next or even find.
Sample code HTML:
<div>
<div class="guides_chapters_button" onclick="surroundtest('[center]', '[/center]');">Center</div>
<div class="guides_chapters_button" style="text-decoration: underline;" onclick="surround('[u]', '[/u]');">u</div>
</div>
<textarea class="guides_chapters_textarea" id="textareamatch" name="matchupm" rows="7" cols="25"></textarea>
JS:
window.surround = function surround(text2,text3){
$("#textareamatch").surroundSelectedText(text2, text3);
}
function surroundtest(text2,text3){
var c = $(this).parent().next('textarea');
c.surroundSelectedText(text2, text3);
}
JS FIDDLE: http://jsfiddle.net/qmpY8/1/
What I need working is surroundtest, the other is an example working but using the id. I would love to replace that one because Im usinc cloned objects.

The this statement in surroundtest applies to the window object and not the element. What you should do is to change the function definition as so:
function surroundtest(element, text2,text3){
var c = $(element).parent().next('textarea');
...
}
And the HTML accordingly:
<div class="guides_chapters_button" onclick="surroundtest(this, '[center]', '[/center]');">Center</div>

If this is the HTML you are going with, then .closest() can also be used to get the textarea element.Like below:
var c = $(element).parent().closest('textarea');

Related

HTML Button Appears as Text after $compile [duplicate]

This question already has answers here:
how can we use $compile outside a directive in Angularjs
(5 answers)
"Thinking in AngularJS" if I have a jQuery background? [closed]
(15 answers)
Closed 4 years ago.
I am trying to create a pop up dialog with two buttons created in JS code with angular. The following code that produces the buttons...
var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="continueAlert()">Continue</button>');
var div = $compile(html);
var content = div($scope);
document.getElementById('dialogboxhead').innerHTML = "header";
document.getElementById('dialogboxbody').innerHTML = "body";
document.getElementById('dialogboxfoot').innerHTML = content;
Gives me the following html text instead of the actual buttons themselves...
[[object HTMLButtonElement], [object Text], [object HTMLButtonElement]]
Am I missing something here that I have forgotten to add in?
The HTML looks like the following...
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div>
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</div>
The $compile method accepts a string argument if you want to provide markup in this way.
Avoid wrapping the input for $compile with anything (ie $(..)). Instead, just pass the html string directly to the $compile() method, and also attach the div via the DOM append() method, and you should find this will work as expected:
var html = '<button ng-click="cancelAlert()">Cancel</button><button ng-click="continueAlert()">Continue</button>';
var div = $compile(html);
...
document.getElementById('dialogboxfoot').append( div[0] );
For more infromation see the usage on the official docs.
Here's a link to a working jsFiddle
It is not wise to mix AngularJS and jQuery this way.
The major problem with this approach is that $compile adds watchers to the specified scope. Those watchers will remain after added elements are removed from the DOM. This will result in memory leaks. If this is a dialog box that is constantly being added and removed -- beware.
But if you must, don't use innerHTML to append compiled content:
̶d̶o̶c̶u̶m̶e̶n̶t̶.̶g̶e̶t̶E̶l̶e̶m̶e̶n̶t̶B̶y̶I̶d̶(̶'̶d̶i̶a̶l̶o̶g̶b̶o̶x̶f̶o̶o̶t̶'̶)̶.̶i̶n̶n̶e̶r̶H̶T̶M̶L̶ ̶=̶ ̶c̶o̶n̶t̶e̶n̶t̶;̶
var foot = document.getElementById('dialogboxfoot');
$(foot).append(content);
The DEMO
angular.module("app",[])
.controller("ctrl",function($scope, $compile) {
var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="continueAlert()">Continue</button>');
var div = $compile(html);
var content = div($scope);
document.getElementById('dialogboxhead').innerHTML = "header";
document.getElementById('dialogboxbody').innerHTML = "body";
var foot = document.getElementById('dialogboxfoot');
$(foot).append(content);
})
<script src="//unpkg.com/jquery"></script>
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</body>

Trouble setting the HTML of a variable in JQuery

What I've done is loaded some HTML from a file and I am attempting to modify some elements within that HTML.
The initialization looks like this:
var id = player_info["ID"];
$("#main_container").append(
$("<div />").attr({class: "player_container", id: "player_" + id}).css("display", "none")
);
// Add all information to the player container
var player_container = $("#player_" + id);
player_container.load("player_layout.html");
With player_layout.html looking like this:
<div class="player_name">
</div>
<div class="player_chips">
Chips:
<br/>
<span class='bidding'></span>/<span class='chips'></span>
</div>
<div class="player_stats">
Wins / Losses
<br/>
<span class="wins"></span>/<span class="losses"></span>(<span class="total_games"></span>)
<br/><br/>
Chips Won / Chips Lost
<br/>
<span class="chips_won"></span>/<span class="chips_lost"></span>
</div>
<button class="player_won">Player Has Won</button>
I then want to modify some of the elements, specifically classes. An example of the way I was initially doing this is:
player_container.find(".player_name").text(player_info['username']);
This wasn't working so I then tried to switch find with children and text with html but that didn't seem to work. I then tried this:
$('> .player_name', player_container).html(player_info['username']);
but that also didn't work. I understand that I can use DOM to grab the childNodes and compare the class names but there are a lot of classes that need modifying and I'd also like to know if this is possible in JQuery. Thanks in advance for any help.
You need to use complete callback method of .load()
var player_container = $("#player_" + id);
player_container.load("player_layout.html", function(){
player_container.find(".player_name").text(player_info['username']);
});

jQuery .size() function doesn´t work with a variable

At many points in my code I need to know how many .page classes are used.
To know this I use $(".page").size()
I want to save this information into a variable.
So I wrote this:
var vari = {
*more variables*
totalPageCount : $(".page").size()
};
The Problem is that vari.totalPageCount always gives 0 back.
With console.log() I get this:
console.log($(".page").size()); // Return 8
console.log(vari.totalPageCount); // Return 0
Edit:
Here is a example how i use it.
JS:
var vari = {
currentPage : 0,
pageAnimations : 0,
animationList : ".fade-in, .fade-out",
totalPageCount : $(".page").size(),
};
var footer = {
html : function(){
var html;
var date = this.date();
for(var i=0; i<vari.totalPageCount; i++){
html = '<span class="pageNumber" id="pageNumber">Folie:'+i+' • '+vari.custom["companyName"]+' • '+date+'</span>';
$("#normalPage"+i).append(html);
}
return;
}
};
HTML:
<body class="presWrapper">
<div class="pageWrapper">
<div class="page startPage" id="startPage">
<h2 class="mainTitle">Lorem</h2>
<h4 class="subTitle">Ipsum</h4>
</div>
</div>
<div class="pageWrapper">
<div class="page normalPage" id="normalPage1">
<div class="content">
<p class="fade-in">HELLO WORLD</p>
</div>
</div>
</div>
<div class="pageWrapper">
<div class="page endPage" id="endPage">
<div class="content">
<p class="fade-out">HELLO SATURN</p>
<p class="fade-out">HELLO WORLD</p>
<p class="fade-in">HELLO WORLD</p>
<p>pTag</p>
</div>
</div>
</div>
</body>
Any suggestions to solve this problem?
vari.totalPageCount Gets evaluated only when it is declared.
As a result it will only have the value of $(".page").size() when it is first run.
Unless you are waiting on document ready the children of .page have not yet been added and it has length 0.
When you later call the console and execute the selector again - you get the true count in the console message - but the stored value has already been calculated as 0 within vari.
length() and size() are equivalent functions in jquery but size has been deprecated so length is the appropriate function to call. But in either case - its likely you are just evaluating the length too early when the vari object is constructed for it to have a meaningful value.
Does the following give you the wrong value for the property:
$(document).ready(function () {
var vari = {totalPageCount: $('.page').length};
console.log(vari.totalPageCount);
});
Relevant documentation
The .size() method is deprecated as of jQuery 1.8.
Use length property instead:
var vari = {
*more variables*
totalPageCount : $(".page").length;
};
Also, make sure you are using this code at the bottom of the script or inside a document ready handler. You won't get accurate information if you try to get it before DOM has been fully setup.
This will increment count for every element with having the page class
var count = 0;
$('.page').each(function() {
count++;
});
var vari = {
totalPageCount: count
};
Working jsFiddle

consolidate javascript function by passing a variable from html object ID such as button ID

Trying to consolidate these three sub functions into one sub function by passing along a variable from the button itself. I currently have four buttons and each button triggers the primary function. Inside the primary function I have the three sub-functions that changes the contents of the div with one of three new html variables. So each button can then change out the div to its own respective content. This code is working now for me no problems, but I figure there has to be a way to just make that sub-function into just one function instead of three by setting the .replaceWith to a global variable. That inside the function there would be a getter that checks the ID of the button that was clicked and passes it to that replaceWith instead.
<script>
$(document).ready(function(){
$("button.first").click(function(){
$('div.switchMeOut').replaceWith(firstHTML);
});
$("button.second").click(function(){
$('div.switchMeOut').replaceWith(secondHTML);
});
$("button.third").click(function(){
$('div.switchMeOut').replaceWith(thirdhtml);
});
});
var firstHTML = '<div class="switchMeOut"><p>First Section Content</div>';
var secondHTML = '<div class="switchMeOut"><p>Second Section Content</div>';
var thirdHTML = '<div class="switchMeOut"><p>Third Section Content</div>';
</script>
<body>
<div id="parentblock">
<h5>Contacts List</h5>
<div class="switchMeOut">
<script> document.write (firstHTML + seconcHTML + thirdHTML); </script>
</div>
</div>
<button id="firstHTML" class="swapper first">Shows First Only </button>
<button id="seconcHTML" class="swapper second">Shows Second Only </button>
<button id="thirdHTML" class="swapper third">Shows Third Only </button>
</body>
So here is what I think should be next but I am definitely missing something.
<script>
$(document).ready(function(){
$("button").click(function(){
// some code here to get the buttons ID element
// and possibly set a variable to that buttons id.
var passThis = button#;
$('div.switchMeOut').replaceWith(passThis);
});
});
Then have each button have their own id. For example:
<button id="firstHTML" class="swapper first">Shows First Only </button>
Any help on this would be appreciated, I dont quite know what I am missing here but I feel like it's pretty close.
Thanks!
You can get the ID of the clicked element like this:
var passThis = $(this).attr("id");
But I think you need to do this too:
var htmls = {
firstHTML: '<div class="switchMeOut"><p>First Section Content</div>',
secondHTML: '<div class="switchMeOut"><p>Second Section Content</div>',
thirdHTML: '<div class="switchMeOut"><p>Third Section Content</div>'
}
And then your switching statement would look like this:
$('div.switchMeOut').replaceWith(htmls[passThis]);
Regarding your comments:
htmls is not an array, its an object. It's called an object in javascript, but people also call them dictionaries, hashes, associative arrays, key/value pairs etc. See: https://en.wikipedia.org/wiki/Associative_array
Also you can't "call" an array or object. You call a function. The best way to phrase that would be "I retrieved/got the value at index 3" for arrays and "I retrieved/got the firstHtml property" for objects.
You can use "eval('variablename') to get the value of the variable. However you can also use eval to get a reference to an object with that ID "eval('id')". So the first thing to do is change the ID of your buttons to a data attribute. Instead of "id='firstHTML'" make it "data-id='firstHTML'". So that when you eval("firstHTML") it knows you mean the variable and not the button object.
And you can get rid of the inline script tag in the "switchMeOut" div and load that using jquery in the same document.ready function.
Heres a fiddle showing it working: http://jsfiddle.net/ub8wz5Lb/
HTML:
<div id="parentblock">
<h5>Contacts List</h5>
<div class="switchMeOut">
</div>
</div>
<button data-id="firstHTML" class="swapper first">Shows First Only </button>
<button data-id="secondHTML" class="swapper second">Shows Second Only </button>
<button data-id="thirdHTML" class="swapper third">Shows Third Only </button>
Javascript:
var firstHTML = '<div class="switchMeOut"><p>First Section Content</div>';
var secondHTML = '<div class="switchMeOut"><p>Second Section Content</div>';
var thirdHTML = '<div class="switchMeOut"><p>Third Section Content</div>';
$(document).ready(function(){
$("button").click(function(){
var id = $(this).data("id");
$('div.switchMeOut').html(eval(id));
});
$('div.switchMeOut').html(firstHTML + secondHTML + thirdHTML);
});

Angularjs - how to bind to an html element appended by javascript code

I want to bind angular event and model to an html element appended by javascript code.
My code is here. https://jsfiddle.net/hq7qk48n/13/
<div ng-app>
<div ng-controller="MyController">
<input type="text" ng-model="text1">
click1
<div id="append"></div>
<p ng-if="clickedTime1">click1 : {{ clickedTime1.toLocaleString() }}</p>
<p ng-if="clickedTime2">click2 : {{ clickedTime2.toLocaleString() }}</p>
<p>{{ text1 }}</p>
<p>{{ text2 }}</p>
</div>
</div>
function MyController($scope) {
$scope.clickedTime1 = null;
$scope.clickedTime2 = null;
$scope.onClick = function () {
var html = '<input type="text" ng-model="text2" name="text"> click2';
$("#append").empty();
$("#append").append(html);
$scope.clickedTime1 = new Date();
}
$scope.onClick2 = function () {
$scope.clickedTime2 = new Date();
};
}
onClick2() doesn't work. and model "text2" is not updated.
How to bind onClick2 function and text2 model?
Need to compile an html element? How?
This is a little tricky because you have an ng-click in your new element. There are 2 things we need to deal with.
Correctly add the element
Make your new element see the scope
First we will start with your call to the method from your element. You will need to add $event to the call
click1
The $event object will give you information about the calling element.
You also need to add it to your method
$scope.onClick=function($event){
Next, your element required use of the scope so we need to turn it into an element. Otherwise just html would be fine.
var el=angular.element('<input type="text" ng-model="text2" name="text"> <a href="#" ng-click="onClick2()"/>click2</a>');
Now you can use a little jquery but exactly on the target element the way angular would do it.
$($event.currentTarget).empty();
$($event.currentTarget).append(el);
At this point you would see your changes but the bindings will not work because it is not attached to the scope so we need to compile it. You will need to add the $compile server to your controller
function MyController($scope,$compile) {
Now we can use the service to compile the new element
$compile(el)($scope);
You should now see everything functioning the way you would expect
function MyController($scope,$compile) {
$scope.clickedTime1 = null;
$scope.clickedTime2 = null;
$scope.onClick = function ($event) {
var el = angular.element('<input type="text" ng-model="text2" name="text"> click2');
$($event.currentTarget).empty();
$($event.currentTarget).append(el);
$compile(el)($scope);
$scope.clickedTime1 = new Date();
}
$scope.onClick2 = function () {
$scope.clickedTime2 = new Date();
};
}
and don't forget to add the $event to your call as well.
I did not use your exact code but I tested this as I answered to verify and it worked perfectly. It might not be best practice to work with the DOM elements in your controller but sometimes it just works. That is how you do it.

Categories