Jquery Math with .return - javascript

var john= 5
$(document).ready(function(){
$('#he').append("<h1>" + $(john + 4).return + "</h1>")
})
I'm trying to get it to come out to nine, but it comes out undefined. How to fix? Yes, I do realize I could just append a "9", but I'm trying to learn how to do very basic math with Jquery, could you show me how to do it through the function?

var john = 5;
$('#he').append('<h1>' + (john + 4) + '</h1>');

Well, you could use something like
var john= 5
$(document).ready(function(){
$('#he').append("<h1>" + (john + 4) + "</h1>")
})

Just change the code to this,
var john= 5
$(document).ready(function(){
$('#he').append("<h1>" + (john + 4) + "</h1>")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="he"></div>

Here you go with one more solution using ES6
var john = 5;
$(document).ready(function(){
$('#he').append(`<h1>${john + 4}</h1>`);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="he"></div>
Hope this will help you.

As the other answers demonstrate, it is for the most part unnecessary to use a return property to display the result of a simple math operation which will evaluate and yield an expression that can be displayed. Nonetheless, assuming a div element with an id of "he", there are a couple of approaches where one could utilize a return property. One could specifically use that property of the event object whose value is:
The last value returned by an event handler that was triggered by this
event, unless the value was undefined.
One could incorporate this property, as follows:
var john = 5;
$(document).ready(function(){
$( "button" ).click(function( event ) {
return john + 4;
});
$( "button" ).click(function( event ) {
$( "#he" ).append( "<h1>" + event.result + "</h1>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>john + 4 equals?</p>
<button>Display Result</button>
<div id="he"></div>
Another interesting thing you can do involves assigning such a property to an element and then use it for the text value for a pair of open and close h1 tags, as follows:
var john = 5;
$(document).ready(function(){
$("#he").prop("return", john + 4);
$("#he").append("<h1>" + $("#he").prop("return") + "</h1>");
});
see live code

Related

Replace selected text inside p tag

I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));

JQuery functions declaration and reusing it

I've got the following jQuery code
$('#rta_ad_yes').click(function(){
$('#rta_ad_pref, #rta_ad_psn').prop('disabled', false);
$('#div_ad_pref, #div_ad_psn').addClass('has-warning');
});
$('#rta_fp_yes').click(function(){
$('#rta_ad_fpref, #rta_ad_fpsn').prop('disabled', true);
$('#div_ad_fpref, #div_ad_fpsn').addClass('has-warning');
});
If you look at the above code it seems i'm doing same coding to achieve the same result.. $('#rta_ad_yes') and $('#rta_fp_yes') in two different pages
sorry to not mentioning my question question how can i declare and call that function provide parameters rather than typing the whole thing again and again.. i dont know how to declare function and reuse it in jquery not very good at jquery
you can try the following code.
function isEmpty (test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-warning');
return false;
}else{
element.removeClass('has-warning');
return true;
}
};
and reuse that like below
var x = isEmpty($('#rta_cl_fn'), $('#div_cl_fn'));
hope that helped
Try
.split()
$('#rta_ad_yes', '#rta_fp_yes').click(function () {
var id = (this.id.split('_')[1] == 'fp')? 'f' : '';//get ad or fp from id
//if it's `fp` than add `f` if not than empty string .
$('#rta_ad_' + id + 'pref, #rta_ad_' + id + 'psn').prop('disabled', function(){
return id.length;//return false if 0 and for 1 return true .
}); //make id out of it
$('#div_ad_' + id + 'pref, #div_ad_' + id + 'psn').addClass('has-warning');
});
I believe you want to abstract that in a function?
var disableAndWarn = function (config) {
$("#" + config.id1 + ', ' + "#" + config.id2).attr('disabled', 'disabled');
$("#" + config.id3 + ', ' + "#" + config.id4).addClass('has-warning');
}
Here is a FIDDLE
Edit: Changed your .prop('disabled', true) into .attr('disabled', 'disabled') since I believe that's what you intended.

Adding and removing elements in Javascript?

I'm trying to make a generator for a mod menu in Call of Duty. I want people to be able to add a menu or delete one. I'm trying to id the menus sequentially so that I can use the text field values correctly. I made it so that if they delete a menu it changes the ids of all the other menus to one lower and same for the button id, but I don't know how to change the onlick event to remove the right element.
Better yet, if there's a better way to do this, I would love to know it.
<script type="text/javascript">
y = 1
function test2()
{
document.getElementById("test2").innerHTML += "<div id=\"child" + y + "\"><input type=\"text\" value=\"menu name\" \><input id=\"button" + y + "\" type=\"button\" value=\"remove?\" onclick=\"test3(" + y + ")\" /></div>";
y++;
alert(y);
}
function test3(x)
{
document.getElementById("test2").removeChild(document.getElementById("child" + x));
for(var t = x+1;t < y;t++)
{
alert("t is " + t + ". And y is " + y);
document.getElementById("button" + t).setAttribute("onclick" , "test3(t-1)");
document.getElementById("button" + t).id = "button" + (t-1);
document.getElementById("child" + t).id = "child" + (t-1);
}
y--;
}
</script>
<input value="testing" type="button" onclick="test2()" />
<div id="test2" class="cfgcode"></div>
I wouldn't worry about re-indexing all of the elements after you add or remove one, that seems a waste. It would be better to simply write a more generic function, rather than one with the element id hard coded into it.
For example, your first function could be written as so:
function genericFunction(el)
{
var html = ''; // create any new html here
el.innerHTML = html;
}
You can then add onclick handlers such as:
myDiv.onclick = function() { genericFunction(this) };
I would also agree with all the commenters above, use jQuery, it makes any code which interacts with the DOM much much simpler.

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

How to access id attribute of any element in Raphael

I'm using Raphael for drawing some elements on a website. The elements include rectangle, line (path). I have given an id to the path element and trying to access it in the onclick event of that line. but when I do an alert of the id, nothing is visible. Following is the code snippet
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
t.node.onclick = processPathOnClick;
}
function processPathOnClick()
{
alert($(this).attr("id"));
}
Can anyone please tell me what is the problem with the above code. Any pointer will be helpful.
Thanks
Are you sure you don't want to write $(t.node).attr('id','Hello'); instead?
Update: someone just downvoted this answer. And I truly feel obligated to point out this way of setting the id isn't particularly good. You would be better off using:
t.node.id = 'Hello';
I wish there was a way to credit Juan Mendes, other than upvoting his comment to this answer.
Try this:
function createLine() {
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.id = 'Hello';
t.node.onclick = processPathOnClick;
}
function processPathOnClick() {
alert($(this).id);
alert(this.id); // This should work too...
}
Basically you are creating a new property called "id" on your Raphael line instance variable "t". It's kind of hacking, in my opinion, but it does the trick just fine.
Try setting the handler using jquery
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
$(t.node).click(processPathOnClick);
}
function processPathOnClick()
{
alert($(this).attr("id"));
}

Categories

Resources