I have a big problem with quotes in java script and html dom.
I want to use just double quotes("), not ' at all!
Here is my code:
<a onclick="aClicked("<span onclick="spanClicked("You clicked me")">I'm an Span</span>")">Add span</a>
<script type="text/javascript">
function aClicked(str) {
$(document).append(str);
}
function spanClicked(str) {
alert(str);
}
</script>
Can anyone help throw kind of these problems!?
Tanks.
here is my original code (it work correctly but I just want to simplfy it and underestand it):
"I call this function with ajax"
<?php
function getTags() {
$values = ['test1', 'test2'];
$valuesString = '';
$baseSpanString = '<span><span class="tag">?</span><a onclick="Tags.Update($(this).parent().parent(), $(this).parent(), "tag");">x</a></span>';
foreach ($values as $tmpValue) {
if(trim($tmpValue) == '') {
continue;
}
$valuesString .= str_replace('?', $tmpValue, $baseSpanString);
}
$xhtml = '
<div>
<input type="text" onkeydown="return Tags.Insert($(this).parent(), $(this), event, \''.str_replace('"', '\\\'', $baseSpanString).'\', \'tag\');"/>
<textarea style="display:none;">'.implode('-', $values).'</textarea>
'.$valuesString.'
</div>
';
return $xhtml;
}
?>
<script type="text/javascript">
Tags = {};
Tags.Update = function(div, span, tagClass) {
div = $(div);
if(!div.length) {
alert('Error');
return false;
}
$(span).remove();
var tagsSpan = $('.'+tagClass, div);
var tagsString = [];
if(tagsSpan.length) {
$.each(tagsSpan, function(index, val) {
tagsString.push($(val).text());
});
}
$('textarea', div).text(tagsString.join('-'));
};
Tags.Insert = function(div, input, event, baseSpanString, tagClass) {
if (event.keyCode == 13)
{
div = $(div);
input = $(input);
if(!div.length || !input.length) {
alert('Error');
return false;
}
var val = input.val();
if(val && val != '') {
input.val('');
var spanString = baseSpanString.replace('?', val);
div.append(spanString);
}
var tagsSpan = $('.'+tagClass, div);
var tagsString = [];
if(tagsSpan.length) {
$.each(tagsSpan, function(index, val) {
tagsString.push($(val).text());
});
}
$('textarea', div).text(tagsString.join('-'));
return false;
}
};
</script>
Two answers:
Your string question
The right way instead
Your string question
' is the feature specifically designed for this. But sometimes this stuff does legitimately come up...
The key is to be aware of what kind of text you're dealing with at each stage:
Within the " of the attribute (onclick="..."), you're writing HTML text, even though what you're writing in that HTML text is JavaScript. So you can use " for quotes if you insist on not using '.
If you need to use a string within your JavaScript code (such as the onclick in the string we're passing aClicked) and insist on not using ', put a \ before the ".
If you need to use a quote within an HTML string within an HTML string (such as the string being passed to spanClicked, which is an HTML string inside a JavaScript string inside an HTML string), then you need something that will end up being " after the entities in the first HTML string are processed. So that's "
So:
<a onclick="aClicked("<span onclick=\"spanClicked("You clicked me")\">I'm an Span</span>")">Add span</a>
Example:
function aClicked(str) {
$(document.body).append(str);
}
function spanClicked(str) {
alert(str);
}
<a onclick="aClicked("<span onclick=\"spanClicked("You clicked me")\">I'm an Span</span>")">Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The right way instead
But again, this is all just a way to make your code complicated unmaintainable; instead, just use jQuery, as you're already using jQuery:
Example:
$("a").on("click", function() {
var span = $("<span>I'm a span</span>");
span.on("click", function() {
spanClicked("You clicked me");
});
$(document.body).append(span);
});
function spanClicked(str) {
alert(str);
}
<a>Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As you are using jQuery use unobtrusive event handlers, for this .on() method can be used. When generating elements dynamically you need to use Event Delegation.
I would also recommend you to use semantically correct elements, thus used <button> element
$("#addSpan").on("click", function() {
$('#container').append("<span class=\"myspan\">I'm an Span</span><br/>");
})
$("#container").on("click", ".myspan", function() {
console.log("You clicked me");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="addSpan">Add span</button>
<div id="container">
</div>
Better make it as a function like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="adds();">Add span</a>
<script type="text/javascript">
function adds(){
aClicked("<span onclick='spanClicked(\"You clicked me\")'>I'm an Span</span>");
}
function aClicked(str) {
$(document.body).append(str);
}
function spanClicked(str) {
alert(str);
}
</script>
Related
The updateValue() method isn't firing and I'm not sure how to even debug this using the browser.
function generateHtmlTableRow() {
var tr = $("<tr></tr>");
$("#results").append(tr);
var someTextData = "test";
tr.append("<td><input type=\"button\" value=\"TestButton\" onclick=\"updateValue(someTextData);\" /></td>");
}
function updateValue(newText) {
alert(newText);
}
The generated html is the problem. It cannot reference a variable in the scope of the generateHtmlTableRow function. So it will work:
function generateHtmlTableRow() {
var tr = $("<tr></tr>");
$("#results").append(tr);
var someTextData = "test";
tr.append("<td><input type=\"button\" value=\"TestButton\" onclick=\"updateValue('" + someTextData + "');\" /></td>");
}
function updateValue(newText) {
alert(newText);
}
$(document).ready(function(){
console.log('log');
generateHtmlTableRow();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
An elegant way to do this is to
Store the someData values in HTML5 data- attributes when you create the <tr>. jQuery has the .data() function for this purpose.
Use a delegated event handler that catches all button clicks inside the <table>. The event handler can then retrieve the data again easily.
function generateTableRow(someData) {
$("<tr><td><button class='test'>TestButton</button></td></tr>")
.data("value", someData)
.appendTo("#results");
}
$(function(){
$("#results").on("click", "button.test", function () {
var value = $(this).closest("tr").data("value");
alert(value);
});
generateTableRow("test 1");
generateTableRow("test 2");
generateTableRow("test 3");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results"></table>
I have this being created by my perl script.
print qq|
\$('textarea[name=category$row[0]]').keydown(function(event)
{
\$("input[value=$row[0]]").attr('checked', true);
});
|;
Somewhere later, I have this, I want to reextract the $row[0] value but I am not sure how in jquery.
print qq|
<script>
\$('#display_category').change(function() {
var text = \$(this).val();
\$('textarea[name^="category"]').each(function() {
var foundvalue = \$(this).val();
if (text == foundvalue)
{
alert("FOUND HERE " + foundvalue);
}
});
});
</script>
|;
how do i reextract the \d+ from category and use it in my if condition?
alert("category1234".match(/\d+/g)[0]);
So something like:
var num = $(this).attr('name').match(/\d+/g)[0];
or (I prefer this one):
var num = $(this).attr('name').replace(/[^\d]/g, '');
Demo: http://jsfiddle.net/karim79/8r8vs/3/
I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>
I'm looking to expand on a recent script i've coded using jquery.
I have this following code
<script type='text/javascript'>
added_departments = new Array();
$("#departments_submit").click(function(){
var depo = $("#depo_list").val();
if(jQuery.inArray(depo, added_departments) != -1)
{
return false;
}
else
{
added_departments.push(depo);
$("#depo_added_list").append("<li>" + depo + "<a href='#' title='"+ depo +"' class='remove_depo'> [X] </a></li>");
var current_value = $("#departments").val();
if(current_value)
{
$("#departments").val(current_value + "," + depo);
}
else
{
$("#departments").val(depo);
}
return false;
}
});
</script>
The above code takes information selected in a select drop down box, adds it to a div to display publicly and also into a hidden form field that processes the data.
i've tried to create now something that will reverse this effect and remove certain selections from the div and the field. which is where i have this code
<script type='text/javascript'>
$(".remove_depo").click(function(){
var removing = $(this).title();
var current_val = $("#deparments").val();
if(current_val == removing) {
$("departments").replace(removing, "");
}
else {
$("departments").replace("," + removing, "");
}
});
</script>
It doesn't cause any errors, but it doesn't do anything either? So I'm really stuck. Any ideas?
EDIT: Updated code
$(".remove_depo").click(function(){
var removing = $(this).attr('title');
var current_val = $("#deparments").val();
if(current_val == removing) {
$("#departments").replace(removing, "");
}
else {
$("#departments").replace("," + removing, "");
}
});
Here is the html
<form method="post" action="javascript:void(0);">Select Departments To Be Added:
<div class="depo_adder">
<select id="depo_list"><option value="">--- INDIVIDUAL TAGS ---</option><option value="blah">blah</option></select>
<button id="departments_submit">Go!</button>
</div></form><form method="post" action="briefings/addbriefing.php">
<div class="form">
<strong>Departments: </strong>
<ul id="depo_added_list"><li>blah [X] </li></ul>
<input name="departments" id="departments" value="blah" type="hidden">
</div>
you're referring to $('departments') - this won't work. You need to specify either an identifierm eg $('#departments') or a class, eg $('.departments)
ah - other answer is also correct, .title() is not a function. You want
$('#foo').attr('title') to get the title.
I have the following html code:
<h3 id="headerid"><span onclick="expandCollapse('headerid')">⇑</span>Header title</h3>
I would like to toggle between up arrow and down arrow each time the user clicks the span tag.
function expandCollapse(id) {
var arrow = $("#"+id+" span").html(); // I have tried with .text() too
if(arrow == "⇓") {
$("#"+id+" span").html("⇑");
} else {
$("#"+id+" span").html("⇓");
}
}
My function is going always the else path. If I make a javacript:alert of arrow variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the arrow variable as a string and not as html.
When the HTML is parsed, what JQuery sees in the DOM is a UPWARDS DOUBLE ARROW ("⇑"), not the entity reference. Thus, in your Javascript code you should test for "⇑" or "\u21d1". Also, you need to change what you're switching to:
function expandCollapse(id) {
var arrow = $("#"+id+" span").html();
if(arrow == "\u21d1") {
$("#"+id+" span").html("\u21d3");
} else {
$("#"+id+" span").html("\u21d1");
}
}
If you do an alert of arrow what does it return? Does it return the exact string that you're matching against? If you are getting the actual characters '⇓' and '⇑' you may have to match it against "\u21D1" and "\u21D3".
Also, you may want to try ⇑ and ⇓ since not all browsers support those entities.
Update: here's a fully working example:
http://jsbin.com/edogop/3/edit#html,live
window.expandCollapse = function (id) {
var $arrowSpan = $("#" + id + " span"),
arrowCharCode = $arrowSpan.text().charCodeAt(0);
// 8659 is the unicode value of the html entity
if (arrowCharCode === 8659) {
$arrowSpan.html("⇑");
} else {
$arrowSpan.html("⇓");
}
// one liner:
//$("#" + id + " span").html( ($("#" + id + " span").text().charCodeAt(0) === 8659) ? "⇑" : "⇓" );
};
Use a class to signal the current state of the span.
The html could look like this
<h3 id="headerId"><span class="upArrow">⇑</span>Header title</h3>
Then in the javascript you do
$( '.upArrow, .downArrow' ).click( function( span ) {
if ( span.hasClass( 'upArrow' ) )
span.text( "⇓" );
else
span.text( "⇑" );
span.toggleClass( 'upArrow' );
span.toggleClass( 'downArrow' );
} );
This may not be the best way, but it should work. Didnt test it tough
Check out the .toggle() effect.
Here is something similar i was playing with earlier.
HTML:
<div id="inplace">
<div id="myStatic">Hello World!</div>
<div id="myEdit" style="display: none">
<input id="myNewTxt" type="text" />
<input id="myOk" type="button" value="OK" />
<input id="myX" type="button" value="X" />
</div></div>
SCRIPT:
$("#myStatic").bind("click", function(){
$("#myNewTxt").val($("#myStatic").text());
$("#myStatic,#myEdit").toggle();
});
$("#myOk").click(function(){
$("#myStatic").text($("#myNewTxt").val());
$("#myStatic,#myEdit").toggle();
});
$("#myX").click(function(){
$("#myStatic,#myEdit").toggle();
});
Maybe you're not getting an exact match because the browser is lower-casing the entity or something. Try using a carat (^) and lower-case "v" just for testing.
Edited - My first theory was plain wrong.