add multiple val in jquery - javascript

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

Related

Change div id on click

I have a few 'headlines' which, when clicked, I would like for them to expand/change colour etc. I shtere any way of changing the div on click of one of the headlines so that whichever one I click will have it's properties changed. One problem is that it will need to be a single instance...When you click on another 'headline' after clicking one previously, the one clicked before hand will need to be changed back.
So...if 'current' is the one that they have just clicked:
<script>
Function ClickedHeadline() {
document.GetElementByID('current').style.width="auto"
document.GetElementByID('current').style.BackgroundColor="#999"
}
</script>
Maybe it can run a script before the one above to tell the div that has the id 'current', will change back and then run the above script...
I don't think I've explained this very well but I hope you can get what I'm trying to do. It just saves me from making a function every time I make another headline along with all the id's, It'll just get extremely confusing after a while.
I agree with the case sensitive and just think is better to add the objet who you want to modify like this :
function ClickedHeadline(o) {
o.style.width="auto";
o.style.backgroundColor="#999";
}
And in the html you just add
onClick="ClickedHeadline(this);"
I think it's better, you can reuse the function now :) .
Javascript is case sensitive, replace with this
function ClickedHeadline() {
document.getElementById('current').style.width="auto";
document.getElementById('current').style.backgroundColor="#999";
}
(i advise of use always semicolon)

Submit form and return result to same page with javascript

Im trying to write a small js script that will let a user input a string of text and then output it wrapped in some html to the page.
I know how to do this with php, but it seems a little bit of an overkill for such a simple action, plus im always keen to learn something new.
I was playing around using document.myform.submit(); but i wasnt sure how to submit the form value to a variable and then output that var to the screen using document.write();
Any ideas how i would do this ?
Ive created a jsfiddle of the problem here - http://jsfiddle.net/pudle/axcLz/
There are many ways to do it. Here is the code that shows one of them:
document.getElementById("myform").onsubmit = function (event) {
var link = document.getElementById("mylink");
var textField = document.getElementById("text");
link.href = textField.value;
textNode = document.createTextNode(textField.value);
if (link.hasChildNodes()) {
link.removeChild(link.lastChild);
}
link.appendChild(textNode);
event.preventDefault();
};
jsfiddle: http://jsfiddle.net/TMJGH/5/
I added an id attribute to the a element to make things easier.
First line says that we want to change the function that handles "onsubmit" event in our form and then we define that function. The "event" argument is used only to call .preventDefault() in the last line which basically means that we don't want the form to be actually submitted.
We need to get access to DOM elements in the javascript code, so I used document.getElementById. Then I set the href attribute to the value of the textField. To change the actual link text I created a new text node with the value of the textField (it is possible to use textNode.innerHTML but that won't escape HTML code if someone inserts it in the text field). Then I check if our a element already has some text in it - if yes, it has to be removed. Finally I append the text element as a new child to our a element.
If you want to append more HTML nodes inside a node you can easily create them with document.createElement('element name') and append them to link. I also have to mention that jQuery makes playing with DOM a lot easier.

How would you refer to javascript function directly in html?

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>

Inserting smilies into div with jQuery

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

choose javascript variable based on element id from jquery

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.

Categories

Resources