So the idea is this. I have an array in the js file as well as a function that refers to a random element from that array. I want to be able to click a button and the text in the span changes to a random element in the array.
I already have a way of doing this. I have a span with an id of "change_equivalently". Then in the javascript file, I have
var Equivalentlys = [
"Equivalently, ",
"Alternatively, ",
"Another way of saying this is that "
];
$('#shuffle').click(function() {
var length = (Equivalentlys.length + 1);
var x = Math.floor(Math.random()*length);
function Equivalently(i){
return Equivalentlys[i];
};
$('#change_equivalently').text(Equivalently(x));
});
My question is that when I write out the html code, I always have to write
<span id = "change_equivalently"> ... </span>
in order to be able to change the words up upon clicking the button.
But I want an easier way.
I tried something like
<var> Equivalently( 1 ) </var>
to see if I could refer to the javascript function, but it didn't work.
How could I go about approaching this?
First of all, the approach you're currently using is better than what you want--it separates presentation from function and is widely regarded as the best practice.
However, you can (but, as I said, probably shouldn't) include code to be called when your element is clicked:
<span onclick="doStuff()"> blarg </span>
If you just want to be able to have JavaScript code that turns into HTML (like PHP or similar templating systems), you won't be able to do it with JavaScript.
Ultimately, the best way is just to use a span to mark the content and add a click event in your script, the way you're doing right now. This is the best semantically: in the html, all you say is that that particular word/position is changeable; you specify how it changes in your code.
Do you mean this?
<script type="text/javascript">
Equivalently(1)
</script>
Related
I want do to click and display in textarea.
The problem is once I click the fullname, the fullname will display in textarea;
and then click ic, the ic will display in textarea but replaced the fullname.
What should I do to make fullname,ic,hp not replace each other? I want to let user click by the variable they want, therefore I didnt do 3 variables insert in one click.
<span onclick=\"insert_user_eh_name('".$row['fullname']."','','');\">".$row['fullname']."</span>
<span onclick=\"insert_user_eh_name('','".$row['ic']."','');\">".$row['ic']."</span>
<span onclick=\"insert_user_eh_name('','','".$row['hp']."');\">".$row['hp']."</span>
function insert_user_eh_name(fullname,ic,phone){
jQuery("#text-area").val(fullname+ ic +phone);}
So, if you're using jQuery, here's the solution you would want:
var insertIntoTextArea = null;
$('.data').on('click', function(){
insertIntoTextArea += $(this).text();
$("#text-area").val(insertIntoTextArea);
});
Now, you can create the identifier any way you would like, but I used a class just to make it easier. One thing to remember is it's not usually a good idea to mix JS and PHP together. It just ends up being a mess and you'll run into so many problems. Also, it's not how jQuery is meant to operate.
That said, what I did was create a click event handler that will know that on click, append it to the textarea's value and make sure it is ADDED to the existing data, rather than overwrite what they previously had in the textarea.
Does this help?
Here's a JSfiddle just in case
embeded JS code you write in HTML is really strange, but if you don't want the string to replace each other in val, why not add them? for example:
// fullname click
var val = $('#text-area').val()
$('text-area').val(val + fullname)
All you need to write is about string process
It could be a rookie mistake, but I've gone over my code enough times doing things such as; pre-pending .select-delete with div, attempted to use document.write("Hello") to see if the event was firing or not.
Here's a link to my jsFiddle: http://jsfiddle.net/gPF8X/5/
I really have no idea what's going on :(.
Any help would be greatly appreciated!
Edit: Linked to the incorrect JSFiddle, relinked to the correct one.
There is no - in your div class name.
<div id="1" class="selectdelete"></div>
$('.select-delete').click( function() {
Got it - id needs to be wrapped in quotes.
var value = $(this).attr('id');
The trigger is firing, but your code is not running because of an error - you're not quoting the string 'id' so it's an undefined value. Use your browser's debugger tool - it will help for this sort of thing.
Beyond that though, I can't say anything further because it's not clear what the desired result is.
Edit There's another issue as well - the selector is not working. You can't use the [ and ] character unquoted inside a jQuery comparison like that. The simplest solution is just not to have those characters in your input names. But you can also use escaping like so: $('select[name=g_country\\['+value+'\\]]').
I know you already accepted my other answer, but I just want to add for the record that there is another way to do it. Specifically, this seems like one of those cases where jQuery is less helpful rather than more. What I would do is change your HTML so the element names were also given as IDs, and then write it like so:
document.getElementById('g_country['+value+']').disabled = true;
document.getElementById('g_url['+value+']').disabled = true;
I'm working on some small chat application. I want to implement smilies over there so when i click on some smiley it will appear in textarea where user enters his message and when user clicks on select i want smilies to appear in div that contains the conversation.
After some workarounds i got to idea that replacing textarea with div contenteditable="true"
doesn't work that well so i did wrap certain smiley name with ':' like :wink: in textarea but still i need to replace :wink: with real span containing image as background.
Problem is i don't see a way to make this dynamically but doing each one by one.
for example:
if ($('.line:contains(":wink:")').length > 0) {
var oldLineHTML = $('.line:contains(":wink:")').html();
$('.line:contains(":wink:")').html(oldLineHTML.replace(/:wink:/gi, '<span class="wink></span>"'));
I have plenty of smilies so doing this very resource expensive function will costs me much and also will cause me lots of problems during maintenance.
How can i do that dynamically? Or maybe you have better solution which will require to re-design... I'm up to it if it is required.
thanks
}
var testString = "test1 :smile: test2 :wink:";
alert(testString.replace(/:([^:]*):/g, '<span class="$1"></span>'));
My suggestion is read every string that is wrapped by colons :[something]:, then convert it into span. So that you don't have to define every smile, and it is easy to maintain.
If you are doing this on page load, then you can do this in a $(document).ready(). Then you can use selector that you have $('.line:contains(":wink:")') and use the $each operator to loop over each one and perform the update. This will cover you for the page load. But if you refactor that $each code into a method, then you can call it each time the text is updated. I think this will give you the best in both cases. Something like this:
function replaceWinks(){
$('.line:contains(":wink:")').each(function(index) {
//Replace the wink here
});
}
$(document).ready(function(){
replaceWinks();
});
I would recommend replacing the winks server side for the page load though. It will be more performant. Also it will avoid content that changes when after the first view.
Jeaffrey Gilbert's idea is good, but I have another one that may be interesting:
write down you winks the way you want(let's say [SmileName]), and when processing the text with jquery, read every one of them, and replace the [ with <div class=" then replace the ] sign, with "></div>, this way, you will end up like this:
using these smilies:
1- [smile]
2- [wink]
3- [shy]
will lead to the following markup
1- <div class="smile"></div>
2- <div class="wink"></div>
3- <div class="shy"></div>
and using CSS, you will give every class of them, a different background image, which is the smile image.
by utilizing this method, every div will lead to displaying your smilies, and you will write the code once, and end up using it wherever you want, without repeating yourself
I feel like this is a simple question, but I am still relatively new to javascript and jquery.
I am developing a site for a touch interface that uses unordered lists and jquery .click functions to take input data. I have a section to input a m:ss time, with 3 divs, each containing a list of digits for time. I need to get the input for each column and set it as a variable. I originally designed the inputs to change form inputs, because I didn't understand javascript very much. It was easy to change the 3 hidden inputs by using div id's, but I can't figure out how to do it now with javascript variables.
Here is my original jquery code...
$("div#time>div>ul>li").click(function() {
var id = $(this).parents(".time").attr("name");
var number = $(this).html();
$("input#"+id).val(number); });
The last line sets one of 3 hidden inputs equal to whatever was clicked. I need to make it so separate variables take the inputs, then I can manipulate those variables however I want.
Here's a short snippet of the html, to have an idea of how jquery grabs it.
<div id="time">
<h1>Time</h1>
<div name="minute" class="time" id="t_minute">
M :
<ul>
The full time html is here: link text
Thanks everyone!
I've been using SO to answer many questions I've had, but I couldn't find something for this, so I figured I would join, since I'm sure I will have more questions along the way.
So I have tried adding the following, and I still can't get it to work right.
window.myValues[id] = number;
event[i].min = myValues["minute"];
event[i].sec = myValues["second"];
event[i].sin = myValues["single"];
event[i].time = String(event[i].min) + String(event[i].sec) + String(event[i].sin);
I tried it both with and without the quotation marks. I have not used window.* for anything, so I'm not very sure how to handle this.
First thing to mention here, don't be unnecessary specific. In your example
$('#time').find('li').click()
should be enough.
If I understand you well, you want to store the some data. You might want to use
jQuery's $.data method. Example:
$('#time').find('li').click(function(){
var $this = $(this);
var name = $this.closest('.time').attr('name');
$.data(document.body, name, $this.html());
});
This would store the html of the clicked li in a global Object, which can be accessed like
alert($.data(document.body, 'minute'));
you should be able to reference the variable from the window[] object, so something like window[id] should do the trick for referencing the variable.
I have this code: [it is a rough example with poor coding, but it illustrates what I want to do.]
<html>
<body>
<script type="text/javascript">
function fun()
{
var divs = document.getElementById('hi');
divs.innerHTML = divs.innerHTML.replace("cake","jump");
alert(divs.innerHTML);
}
</script>
<div id="hi">
<span onclick="fun('cake');">Mer<span onclick="fun('cake');">Mer</span></span>
</div>
<a onclick='fun()';)>Click</a>
</body>
</html>
When I click on the <a> i want to change the onclick parameter within fun() from 'cake' to 'jump'. I do not want to use the setAttribute() method as my real example has several nested tags and I want to replace 'cake' in several different places.
I want the innerHTML.replace() function to work to do this but, alas it doesn't function as I want it to. How do I replace text within innerHTML?
Forget it. Never hack around with the innerHTML, there's no guarantee it will be in any particular format, you're very likely to mess up the markup by replacing the wrong thing, and even if it works, you're serialising the document content into a string, hacking it and then recreating the entire content from the string again, instead of just replacing a particular thing you're interested in. This is slow and loses all non-serialisable data (like form field values, JS references and assigned event handlers).
In general DOM methods are much more reliable for altering page content. It's what they were designed for. Use them, and use the DOM Level 1 HTML properties in preference to setAttribute which is badly broken in IE. This goes double for event handler attributes. Trying to hack at JavaScript code inside an attribute value inside an HTML string is insanity, even if it worked.
There is no need whatsoever to replace any page content. You could implement your example much more easily with a simple variable:
<div id="hi">
<span>Mer<span>Mer</span></span>
</div>
<a id="foo">Click</a>
<script type="text/javascript">
var potato= 'cake';
document.getElementById('foo').onclick= function() {
potato= 'jump';
return false;
};
var spans= document.getElementById('hi').getElementsByTagName('span');
for (var i= spans.length; i-->0;) {
spans[i].onclick= function() {
alert(potato); // do whatever with the variable
};
}
</script>
First, you have an error in your HTML:
<a onclick='fun()';)>Click</a>
What's with the ;) outside the attribute value?
Next...
[...] method as my real example has several nested tags and I want to replace 'cake' in several different places.
This means you really, really don't want to use innerHTML and replace(). It will screw up. Use an HTML parser of sorts; walk the DOM recursively... anything other than replace.
Within the scope of your specific example, I suggest using a variable to hold the value of cake and jump instead.
Change your replace call to use the RegEx "global" flag:
divs.innerHTML = divs.innerHTML.replace(/cake/g,"jump");
That said, if you're using this for more than a quick test, you should use DOM objects to accomplish what you would like to do. Otherwise, this will get ugly really fast.
Also, it wouldn't hurt to change your <a> tag code:
<a onclick='fun(); return false;')>Click</a>
(The return false; is optional, but good practice.)
The easiest way to change the onclick parameter is to make it a variable instead of a string literal. Here I'm using a variable called food:
<script type="text/javascript">
var food = "cake";
function change()
{
food = "jump";
}
</script>
<div id="hi">
<span onclick="alert(food);">Mer<span onclick="alert(food);">Mer</span></span>
</div>
<a onclick='change()'>Click</a>