...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
May 16, 2012

Jquery, get label value inside a user control

Question by LuisEValencia

I need to make a calculation in an asp.net page with the value from a usercontrol label.

the user control label is:

 <asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>

I include it like this:

<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />

And my jquery function is something like:
Please see point 1 and 2.

<script type="text/javascript">
        $(document).ready(function () {
            alert('call function to do calculation here');
            // 1.   Find in the vehicle information user control the invoiced ammount label
            // 2.   Find the vat excluded value **after** it was typed in the textbox
            // 3.   If invoiced ammount is greater than zero, then
            // 3.a  Find Label Percentage 
            // 3.b  Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
        });
  </script>

HTML generated:UPdate1

For the label:

 <span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>

For the textbox:

<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />

Update 2:

<script type="text/javascript">
        $(document).ready(function () {
            alert('call function to do calculation here');

            $("#TxtVatExcluded").keypress(function() {
                var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
                var vatexcluced = $("#TxtVatExcluded").val();
                var lblPercentage = $("#MainContent_LblPercentage");
                if (invoiceprice > 0) {
                    lblPercentage.text((vatexcluced / invoiceprice) * 100);
                }
            })

            // 1.   Find in the vehicle information user control the invoiced ammount label
            // 2.   Find the vat excluded value after it was typed in the textbox
            // 3.   If invoiced ammount is greater than zero, then
            // 3.a  Find Label Percentage 
            // 3.b  Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
        });
  </script>

Answer by Imdad

var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);

UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code

var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
  $("#TxtVatExcluded").val(label_text);
}

Answer by Starx

You can use the rendered ID of the elements to get the values using jQuery

var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();

Later when the calculation is complet, you can update the label text as

$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");

Update:

To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event

$("#myinputbox").keypress(function() {
    var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
    var tbox = $("#TxtVatExcluded").val();
    //... so on
}

Update 2:

Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.

        $("#TxtVatExcluded").keypress(function() {
            var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
            var vatexcluced = $("#TxtVatExcluded").val();
            var lblPercentage = $("#MainContent_LblPercentage");
            if (invoiceprice > 0) {
                lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
            }
        })
Read more
May 15, 2012

Passing variables as parameters from one function to multiple functions

Question by user976813

In my script I’ve got a function createEl() where I declare 2 variables and call 2 other functions passing those declared variables to those 2 functions.

By clicking on one link first function is supposed to add 10px to divp‘s height. By clicking on another link the second function should deduct 10px from div‘s height.

It doesn’t work as expected though. I believe I have to call those 2 functions from my first functions in some different manner? Now the result is that whichever link I click those 10px are always deducted. Please help.

P.S. I am seeking for an option without global variables, rather just pass the variables as parameters from one function to multiple functions.

HTML:

<a href="" onclick="createEl();return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="createEl();return false;">Smaller</a>

<div id='box'></div>

JavaScript:

function createEl() {
    var x = document.getElementById('box');
    var h = x.offsetHeight;

    large(x,h);
    small(x,h);
}

function large(x,h) {
    x.style.height = h + 10 + "px";
}

function small(x,h) {
    x.style.height = h - 10 + "px";
}

Answer by Starx

Update your HTML to send an identifier parameter to the function call.

<a href="" onclick="createEl('large');return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="createEl('small');return false;">Smaller</a>
<div id='box'></div>

JavaScript:

function createEl(funcName){

        var x = document.getElementById('box');
        var h = x.offsetHeight;

        if(funcName =="large") large(x,h); //depending on the parameter call the required function
        else small(x,h);
}
Read more

How to set top position using jquery

Question by Rajanikant Shukla

I am creating custom div scroller and want to set top position of content div. My jquery code is as bellow:-

containerOuterHeight=$("#messagePopUpContainer").outerHeight();
            contentOuterHeight=$("#content").outerHeight();
            contentTopPosition=$("#content").offset().top;
            alert("contentTopPosition"+contentTopPosition);
            alert(contentTopPosition-(containerOuterHeight/20));
            $("#content").offset().top=contentTopPosition-(containerOuterHeight/20);
            //$("#content").css("top",( contentTopPosition-(containerOuterHeight/20) ) + "px");
            alert("contentTopPosition"+$("#content").offset().top);
            //alert("Fontsize"+$('#content').css('font-size') );

and html is :-

<div id='messagePopUpContainer' style='background-color:#ffffff; overflow: hidden;'>
<a href='javascript:void(0);' id='popupanchor' onkeydown='PopupKeyHandler("' + elmId + '");'></a>

<div id='content' style='width:350px'>' + methods.settings[elmId].text + '</div >
<div id='popupReturn'>Return</div></div></div>'

can you suggest me how to do this. any help will be appriciated.

Thanks

Answer by Starx

Accessing CSS property & manipulating is quite easy using .css(). For example, to change single property:

$("selector").css('top', '50px');
Read more

Redraw table if search bar is empty

Question by Tural Teyyuboglu

Based on this discussion, added code below into my JS code to enable filtration to be triggered by pressing the enter key instead of keyup or delay.

jQuery.fn.dataTableExt.oApi.fnSetFilteringPressEnter = function (oSettings) {
    var _that = this;

    this.each(function (i) {
        $.fn.dataTableExt.iApiIndex = i;
        var $this = this;
        var anControl = $('input', _that.fnSettings().aanFeatures.f);
        anControl.unbind('keyup').bind('keypress', function (e) {
            if (e.which == 13) {
                $.fn.dataTableExt.iApiIndex = i;
                _that.fnFilter(anControl.val());
            }
        });
        return this;
    });
    return this;
}

/* Example call */
$(document).ready(function() {
    $('.dataTable').dataTable().fnSetFilteringPressEnter();
} );

Now what I want to do is, when user removes keyword from search bar, I want to redraw table. Currently it doesn’t redraw without pressing enter button. How can I achieve this result?

Answer by Starx

I think its safe to do on the keyup event of keyboard, unlike only triggering on the enter key press.

anControl.off('keyup').on('keypress', function (e) {
        $.fn.dataTableExt.iApiIndex = i;
        _that.fnFilter(anControl.val());
});

Also, note I have used on() and off() for delegation instead of bind and unbind which are deprecated as of jQuery 1.7

Or, you can create a completely different handler for the specific case, where all the keywords are deleted on the text box.

    anControl.off('keyup').on('keypress', function (e) {
        if (e.which == 13) {
            $.fn.dataTableExt.iApiIndex = i;
            _that.fnFilter(anControl.val());
        }
        if(anControl.val().length == 0) {
               //redraw table
        }

    });
Read more

Is there a way to use <![if !(IE 8)]> within PHP?

Question by HudsonHawk

Sorry for the confusing title, I didn’t know how I could describe it better.

Anyways, here is the ‘problem’ I am currently using for my website Cufon. Which works great. However with Internet Explorer 8 it becomes really slow. Therefor I decided to use:

<![if !(IE 8)]>
<script type="text/javascript" src="js/myriad-pro.cufonfonts.js"></script>
<script type="text/javascript">Cufon.replace('.example1') ('.example2') ('.example3') ('.example4') ('.example5');
</script>
<![endif]>

This works great, however not for everything. Some parts of the scripts, which calls Cufon in the script itself, it doesn’t work and Cufon will still be displayed in IE8 (with all negative results from it).

Several included scripts / parts have the following code in it:

<?php
echo "<script language="javascript" type="text/javascript">";
echo "$(document).ready(function() { Cufon.replace('.orderpart1') ('.orderpart2') ('.orderpart3'); });";
echo "</script>";
?>

Now is it possible to make a same statement as with within the PHP script(s)? So if it’s any browser other than IE8 it will load the Cufon, but if it’s IE8 it will not load Cufon?

Hopefully someone understands what I mean here, cause it’s kinda hard to explain for me… 🙁

Answer by J-P

<?php
echo "<![if !(IE 8)]>";
echo "<script language="javascript" type="text/javascript">";
echo "$(document).ready(function() { Cufon.replace('.orderpart1') ('.orderpart2') ('.orderpart3'); });";
echo "</script>";
echo "<![endif]>";
?>

is that it ? Or did I misunderstand your request ?

Edit:
Another way, as I see that you are using jQuery, could be using jQuery browser detection :

<?php
echo "<script language="javascript" type="text/javascript">";
echo "if ( $.browser.msie && $.browser.version <= 8 ) {";
echo "$(document).ready(function() { Cufon.replace('.orderpart1') ('.orderpart2') ('.orderpart3'); });";
echo "}";
echo "</script>";
?>

Please note that this feature is deprecated :

This property is available immediately. It is therefore safe to use it to determine whether or not to call $(document).ready(). The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery.

If you know exactly what kind of feature are needed and aren’t implemented in IE8 i would recommend using $.support which is meant for feature detection rather than browser detection.

Answer by Starx

Basically, you can do this by filtering guest’s USER AGENT[docs]. You can get this from the server variable.

$ua = $_SERVER['HTTP_USER_AGENT'];

USER agent contains all the necessary information of the guest who is opening the page. A simplest usage of this technique I know so far is:

if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT'])) {
    //do something
}
Read more

jQuery function enable a div

Question by user1213807

I’m this code embed my js file for win key close. This codes:

jQuery(document).keydown(function(e){
    alert(e.keyCode); // replace "37" below with the windows key code
    if (e.keyCode == 37) { 
       alert( "windows key pressed" );
       return false;
    }
});

Working good. But i want only work 1 div. How can i do this?

Answer by mprabhat

Add the selector instead of document

jQuery('selector') instead of jQuery(document)

where selector can be anything like id, class e.t.c

Demo which uses selector as id

Another Demo will work for only one input inside a div.

Div Demo will work only for first div

Disabled for Div will work only for span not for div

Disabled for input in div will work for all input if they are not inside a div

Answer by Starx

Use your div selector instead of document selector.

jQuery("#yourdivid").keydown(function(e){
    alert(e.keyCode); // replace "37" below with the windows key code
    if (e.keyCode == 37) { 
       alert( "windows key pressed inside div" );
       return false;
    }
});

To disable a div, you can simple use $("#yourdivid").prop('disabled', true);

Read more

document.documentElement used in "in" statement

Question by Gautham Renganathan

I saw this piece of code in jQuery’s source. I am a novice in javascript and I would like to know how this works.

if ( "getBoundingClientRect" in document.documentElement ) {
// do something...
}

How is it different from

if(document.documentElement.getBoundingClientRect) {
// do something...
}

…?

Answer by T.J. Crowder

That’s an expression using the in operator. The in operator checks to see if the target object has a property with the given name (directly, or via the object’s prototype).

What it’s doing is seeing if document.documentElement has a property with the name getBoundingClientRect (which is a handy function jQuery would like to use if the browser provides it).

How is it different from if(document.documentElement.getBoundingClientRect) { // do something... }

in doesn’t require fetching the value of the property, just checking that it exists. Also note that the second form you list would test the truthiness of the value of the property. In the case of a function like getBoundingClientRect that would be fine, but if you wanted to test something whose value might come back falsey (0, "", etc.), it would fail even though the property exists.

You’ll see this sort of thing a lot when doing feature-detection. For instance, if you want to know if a browser supports the HTML5 placeholder attribute:

if ('placeholder' in document.createElement('input')) {
    // Yes, it does
}

This is an example where we couldn’t use the form if (document.createElement('input').placeholder) because if the condition were false, we wouldn’t know whether it was false because the property didn’t exist, or false because the property existed but had a falsey value (and the default value for placeholder is "", which is indeed falsey).

Gratuitous link to list of feature detections.

Answer by Starx

The in operator checks to see if a given property is or present within a specified object or not. SO,

if ( "getBoundingClientRect" in document.documentElement ) {
// do something...
}

will check if getBoudingClientRect property is available in document.documentElement Object.

Moreover, you might want to read the article form John Resig himself, who has well explained, Why it is used.

Read more
May 14, 2012

How to count whitespaces as a childnodes?

Question by user1394479

Whitespace count as empty text element in a DOM.
How can I count these whitespaces?

for example

<body>

    <div>

    </div>

    <div>

    </div>

</body>

how many whitespaces(childNodes) inside the body element?

how many whitespaces(childNodes) inside each div element?

Answer by Starx

If you are trying to see how many elements are empty? Then I am giving you a jQuery solution instead.

bodyChild = $("body :empty").length;
divHcild = $("#divid :empty").length;

Using them, you can know what many elements are completely empty inside an element.


Update:
To get all the child element, you can use something like this

Body:

var children = document.getElementByTagName('body').childNodes;
Read more

jquery ajax cant loop thru the found data

Question by user759235

I want to loop thru a file which is loaded with ajax, but it won’t loop, i have tried a couple of things but I cant get it to work.

// jquery

$.ajax({
    url: 'file.html',
    type: "GET",
    dataType: "html",
    success: function(data) {

        $(data).find('div').each(function(i){
            alert('found')
        });

    },
    error: function(){
        alert('oeps...')
    }                           
});

// file.html

<div>
// content goes here
</div>

<div>
// content goes here
</div>

<div>
// content goes here
</div>

...


...    

Answer by Rocket Hazmat

You need to change .find to .filter. This is because .find searches the children descendants of all the elements, but since your html file is just <div>s, you need to use .filter to find them.

DEMO: http://jsfiddle.net/zuPVp/

Answer by Starx

You dont need to specify html as the datatype, it is not needed.

SO, remove the following line.

dataType: "html"
Read more

Save multiple form

Question by Kioko Kiaza

Having this Entity for example:

<?php

namespace GitekHotelBundleEntity;

use DoctrineORMMapping as ORM;

/**
 * GitekHotelBundleEntityProduct
 *
 * @ORMTable()
 * @ORMEntity(repositoryClass="GitekHotelBundleEntityProductRepository")
 */
class Product
{
    /**
     * @var integer $id
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $name
     *
     * @ORMColumn(name="name", type="string", length=100)
     */
    private $name;

How to build a Form to save like 10 products on a row? I want a form with a “+” button and dinamically add line and submit all products in a row.

any help or clue?
thanks in advance

Answer by Farhan Ahmad

You could use Javascript(jQuery) to add the form elements to your page dynamically when you click the “Add” button. Something like this:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#btnAdd').click(function() {
                var num     = $('.clonedInput').length;
                var newNum  = new Number(num + 1);

                var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);

                newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
                $('#input' + num).after(newElem);
                $('#btnDel').attr('disabled','');

                if (newNum == 5)
                    $('#btnAdd').attr('disabled','disabled');
            });

            $('#btnDel').click(function() {
                var num = $('.clonedInput').length;

                $('#input' + num).remove();
                $('#btnAdd').attr('disabled','');

                if (num-1 == 1)
                    $('#btnDel').attr('disabled','disabled');
            });

            $('#btnDel').attr('disabled','disabled');
        });
    </script>
</head>

<body>

<form id="myForm">
    <div id="input1" style="margin-bottom:4px;" class="clonedInput">
        Name: <input type="text" name="name1" id="name1" />
    </div>

    <div>
        <input type="button" id="btnAdd" value="add another name" />
        <input type="button" id="btnDel" value="remove name" />
    </div>
</form>

</body>
</html>

Reference
Then when the form is posted, you can walk through the $_POST array.

Answer by Starx

That is very least amount of code, to see your working process.

But basically such tasks are solved, by storing all the information on the session as a multidimensional array and finally inserting them one by one on the last point.

Read more
...

Please fill the form - I will response as fast as I can!