javascript onclick not working with parameters - javascript

I just want the user to click on a name and then it pops (alerts) some info. in the a tag if i don't pass any parameter it does alert something, it otherwise won't alert anything, even if i put something like this
<a href='javascript:sayThis('hi');'>
here's my html code (generated by some PHP):
PHP:
function showThis($color, $withFunctionYesOrNo, $first_levelIdFunction, $first_levelNameFunction, $first_levelLastNameFunction, $agent_email){
if($withFunctionYesOrNo == 'yes'){
$showThis = "<br>
<div>
<div style='margin-left:5%; border-left:6px solid ".$color."'>------
<a href='javascript:sayThis('".$agent_email."');'>
".$first_levelLastNameFunction.", ".$first_levelNameFunction." (ID: ".$first_levelIdFunction.")
</a>
<input type='submit' class='more' id='more' value='+' onclick='agentsBelow(".$first_levelIdFunction.")'>
</div>
<div style='margin-left:7%;' id=".$first_levelIdFunction."></div>
</div>";
}
return $showThis;
}
here is my JS code:
function sayThis(email){
alert(email);
}

First, I'd like to say that I would never use your coding practice. Not only do you have quote issues all over the place, but onclick the Event Object is passed to your Event Handler agentsBelow(). In these situations I do my code like this:
document.getElementById('more').onclick = function(e){
e = e || event; // don't even need to use the `e` argument above or this if not using the Event Object
agentsBelow('whatever');
}
Really, the style I'm showing is the way you should code, where your JavaScript is separate from your HTML. Of course, if you insist, you could just wrap your function within an Anonymous function in your HTML. Bad HTML practice:
onclick='function(){agentsBelow(\"you have String issues too\")}'
Note that you don't need to concatenate in double quotes. By the way:
onclick='agentsBelow(".$first_levelIdFunction.")'
using bad practice, should be:
onclick='function(){agentsBelow(\"$first_levelIdFunction\")}'
You are passing a variable to your JavaScript, not a String.
onclick='agentsBelow(".$first_levelIdFunction.")' could evaluate to:
onclick='agentsBelow(youFirstLevelIdFuntionVarResultIsNotaString)'
Still that wouldn't wouldn't work, since the Event Object would pass in.

Change this
<a href='javascript:sayThis('hi');'>
to this:
<a href='javascript:sayThis("hi");'>

change this
<a href='javascript:sayThis('".$agent_email."');'>
to
<a href='javascript:sayThis(\"".$agent_email."\");'>

Related

How to deal with 3 times quotation marks in a onclick proberty of an element

I have a little problem: In my project I tried to make a like button and defined a button attached to a function via onclick proberty. But now it looks like this:
<div class="post-container">
<button class="{% if post.liked %}color-blue{% else %}color-white{% endif %}" id="post_{{ post.id|stringformat:'s' }}" onclick="postLike('{{ post.id|stringformat:'s' }}')"> {{ number_of_likes }} Like{{ number_of_likes|pluralize }}</button>
</div>
Visual Studio Code red-marks this and I am not really sure how to handle these this, since I am getting an error on onclick in the Console when I press the button...
Inline handlers like you're currently using are universally considered to be terrible practice, and one of the reasons for that is because they have very ugly quote escaping problems when passing string parameters. (They also require global pollution and have a demented scope chain.)
Put the post ID into a data attribute instead, and attach listeners to each element in standalone JavaScript elsewhere. For example, if you're starting with
<button class="myButton" onclick="postLike('{{ post.id|stringformat:'s' }}')">
change to
<button class="myButton" data-post-id="{{ post.id|stringformat:'s' }}">
and retrieve the post ID from the button when clicked. After the HTML contains all the buttons, run the following JS:
for (const button of document.querySelectorAll('.myButton')) {
button.addEventListener('click', (e) => {
postLike(e.target.dataset.postId);
});
}
You will have to tweak the selector string .myButton depending on the HTML markup around your buttons.
Another option, using event delegation on a container of all the buttons:
container.addEventListener('click', (e) => {
if (e.target.dataset.postId) {
postLike(e.target.dataset.postId);
}
});
To deal with 3 times quotation marks you need to switch between single and double quotes. Try doing this:
onclick='postLike("{{ post.id|stringformat:'s' }}")'

How can I get an HTML tag’s value to send an HTML.Action()

I have these lines of code:
<span
class="close-modal"
onclick="#Html.Action("SaveNotes", "CallCenter", new { activityId = item.callIdKey, noteText = "test1" })">
×
</span>
Notes: <br />
<textarea name="paragraph_text" rows="5" style="width:90%">
#item.NoteText
</textarea>
I would like to replace test1 from the noteText route variable and instead change it to whatever the value in the <textarea> tag is.
Is there an elegant way of doing this without writing a giant block of jQuery code?
#Html.Action() renders a partial view as an HTML string during page processing (on the server side). It doesn't exist any more in the markup, once the page is sent to the browser. You can't do what you are trying to do this way. At the very least, I'm sure you don't want to render a partial view inside the onclick event of your <span> tag.
Why not instead use an HTML helper for the <textarea> tag? Then you can get whatever value the user typed into it on the server code. You'll want to make the form post itself back to the server on the close-modal element:
<span class="close-modal" onclick="$('form').submit()">×</span>
<form method="post" action="#Url.Action("SaveNotes", "CallCenter", new { activityId=item.callIdKey }">
Notes: <br />
#Html.TextArea("noteText", item.NoteText, new { rows="5", style="width:90%" })
</form>
This assumes you have jQuery already (a common assumption with ASP.NET). You may not need the <form> tags if you already have a form on your page.
A #gunr2171 notes in the comments, the only way to dynamically update a link once it's been rendered to the browser is via some form of client-side scripting, typically JavaScript. In your case, I'd recommend doing something like this:
<span
class="close-modal"
data-href-template="#Url.Action("SaveNotes", "CallCenter", new {activityId = item.callIdKey, noteText="{note}"})"
>
×
</span>
Note: As #HBlackorby notes in his answer, you shouldn't be using #Html.Action() here; I assume you meant #Url.Action().
This way, your JavaScript has a template (data-href-template) that it can work against with a clearly defined token ({note}) to replace, instead of needing to parse the URL in order to identify where the previously replaced text is. Otherwise, you potentially end up in a scenario where you type e.g. CallCenter into your <textarea /> and it's now an ambiguous reference that you can't just blindly replace. Or, worse, you type 'a' and it's really ambiguous.
If you are already using jQuery on your site, the actual replacement might be done using something along the lines of:
$(document).ready(function () {
$('span.close-modal').click(function() {
var noteInput = $('textarea[name="paragraph_text"]');
var encodedNote = encodeURI(noteInput.text());
var template = $(this).data("href-template");
var targetUrl = template.replace("{note}", encodedNote);
window.location.href = targetUrl;
});
});
You can also do this without jQuery, obviously—and should if you're not already depending on it. The point is to illustrate that this doesn't necessarily need to be a "giant block of jQuery code". In fact, this could be done in just a few lines—and probably should be. I deliberately broke it out into multiple steps and variables for the sake of readability.

how to clear an input field onclick of an image?

I'm creating a form inside a foreach loop. What actually I want is that... how can I clear the value of a particular input field on click of an image.
Following is the code which is inside loop. It has many more form fields. But I want to clear a particular input field, because I'm fetching the data from database, making changes and then saving it again.
<a onclick="clearField("<?php echo "field_id".$language["language_id"]; ?>")"
href="javascript:noAction();"><img src="view/image/delete.png">
</a>
<input type="text"
id="<?php echo 'field_id'.$language['language_id']; ?>"
name="file_name[<?php echo $language['language_id']; ?>]"
value="<?php echo isset($document_description[$language['language_id']]) ? $document_description[$language['language_id']]['file'] : ''; ?>"
readonly="readonly"/>
Following is the javascript which is used for above function--
<script>
function clearField(input,val) {
if(input.value == val)
input.value="";
};
</script>
EDITED :- there is one more problem with the following statement --
all quotes which are used inside this statement are not proper. i mean to say that the code do not gets parsed due to some missing or some additional quotes. So please tell me how to correct this.
<a onclick="clearField("<?php echo "field_id".$language["language_id"]; ?>")"
href="javascript:noAction();"><img src="view/image/delete.png">
</a>
You can do this very easily in javascript
HTML code
<img src="http://www.mricons.com/store/png/45804_11386_128_button_cancel_icon.png" height="35" width="35" onclick ="change()" />
<input type="text" name="name" value="name" id="ghd" />
JAVASCRIPT code
function change(){
var ab = document.getElementById('ghd').value;
document.getElementById('ghd').value = "";
$('#ghd').val('dsds');
}
Following is the link to jsfiddle also---
http://jsfiddle.net/nnRV5/
Hope it helps you!!
Try Following
<img src="view/image/delete.png" onclick="clearInput();">
<script>
function clearInput(){
document.getElementById('input_id').value = '';
}
</script>
Rather than using an anchor you could just listen for the click event on the image itself, like this:
<img id="clickable_image" src="delete.png" alt="Clear input text" />
<input id="the_input_to_clear" ... other attribs here ... />
<script>
(function(){
var image = document.getElementById('clickable_image'),
inputField = document.getElementById('the_input_to_clear'),
clickHandler = function() {
inputField.value = '';
};
if (image.addEventListener) {
// this attaches the event for most browsers
image.addEventListener("click", clickHandler, false);
} else {
// this attaches the event for IE...
image.attachEvent("onclick", clickHandler);
}
})();
</script>
From an accessibility perspective a clickable image that controls a form field is not good practice, but at least you're not having to worry about having an anchor that goes nowhere. If you want to improve the accessibility you might like to use a button element, and style it with a background image something like: http://jsfiddle.net/3vPpt/3/
The Javascript in my example dynamically attaches the click event to the image rather than specifying the function in the element's onclick attribute. This is to separate presentation from behaviour logic and is considered best practice.
The funky (function(){})(); notation executes the script immediately, but does not leak the variables created (image, inputField, clickHandler) into the global scope. This is also a best practice thing, and will prevent your script interfering with other code on the page.
Try this:
<script>
function clearField(input,val) {
if(document.getElementById(input).value == val){
document.getElementById(input).value = '';//This will clear the field
}
</script>

how to pass the value of <a> tag to a javascript function

First of all my question is, does a tag in html stores a value like input type = "text" does?
Secondly, I have a links like this let say:
<a href="#" >A</a>
<a href="#" >B</a>
<a href="#" >C</a>
I want to pass for each of the link their value let say A, B, C.
What i do is this:
A
<script type="text/javascript">
function sendVal(letter){
alert(letter);
}
</script>
But unfortunatelly i dont get A , but i get its href, how would i get the letter??
Any idea?
try this.
A
function sendVal(letter){
alert(letter);
}
A
here you go as JS only
A
function sendVal(letter){
alert(letter.text);
}
If you want cross browser compatibility i would really use jquery, otherwise you'll have to do lots of checks to see which to use.
If you are not limited to JS(as per client request) and this is a learning project you should really look at: jQuery

how to pass embed code in javascript

<a href="" onClick="return select_item(<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>')>
The above returns an "unterminated string literal" error.
How to solve this issue. This function is inside smarty template.
Thanks for every answer
I've also run into situations with Smarty where it tries to evaluate Javascript as Smarty template code.
In that case, you need to surround the Javascript with {literal}{/literal} tags.
However, in your case, I think you're missing a single-quote at the beginning of select_item( and a double-quote at the end of the onClick event:
<a href="" onClick="return select_item('<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>')">
I'm not 100% sure if you really need to backslash-escape the double-quotes that are part of the <embed HTML.
For that amount of markup, I find it easier to read and debug if you don't do it inline as part of the onClick event. I use PrototypeJS so I'd handle it like this
Click Here
//Handle the click event of the above a tag
Event.observe($('doSelectItem'), 'click', function(event) {
var markup = '<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>';
if( select_item(markup) ) {
//select_item returns true, so let the click event continue
}else {
//select_item returned false so cancel the click event.
Event.stop(event);
}
});
If you get
unterminated string literal
then it basically means that you have started a String, but never ended it. E.g.
var foo = "bar;
Solution is obvious: terminate it:
var foo = "bar";
Another common cause is using the same quotes inside the String as with which the String is wrapped:
var foo = "my mom said "go out!" to me";
You need to escape such quotes then:
var foo = "my mom said \"go out!\" to me";
In your specific case you have " inside the HTML string which is on its turn wrapped inside another "s of the onclick attribute. So:
<a href="" onClick="return select_item('<embed src="player.swf" ...
needs to be replaced by
<a href="" onClick="return select_item('<embed src=\"player.swf\" ...
It looks like ') is missing at the end of your onClick event, hence the JavaScript error. You also need to escape the double quotes. The line should look like:
<a href="" onClick="return select_item('<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\">');">
There is so much confusion about escaping quotes in javascript and HTML, especially when they are mixed like this.
Straight off the bat, try to avoid this situation in the first place. HTML is for markup, Javascript is for behaviours. That said...
In Javascript, you escape quotes with a backslash. This is so that when javascript interprets the string it knows where it ends.
var name = 'O\'Reilly';
In HTML, you use ampersands and a character code.
O"Reilly
Just remember that when you are writing code in your HTML, it's not being interpreted by javascript, it's being interpreted by the HTML parser. To a HTML parser, a backslash is just a regular character.
<a onclick="foo("bar");">
Now you see why I'd recommend avoiding the situation in the first place. Here's the alternative:
<a id="myLink">
<script type="text/javascript">
document.getElementById('myLink').onclick = function() {
foo('bar');
};
</script>

Categories