May 29, 2011

jQuery $.post doesn't pass what button were pressed

Question by Cheburek

Recently I’ve stuck with a problem where $.post does not send information about button which were pressed.
I.e. we have a form with two buttons.

<form method="post"  action="/home/index">

  <input type='hidden' name='data1' value='value1' />

  <button name="button1" type="submit">First</button>
  <button name="button2" type="submit">Second</button>

</form>

$(document).ready(function() {
    $('#formId').submit(function () {
        var f = $(this);
        var action = f.attr("action");
        var serf = f.serialize();
        $.post(action, serf,
        //onreturn
          function (data) {
                //do something here on success
              },
              'json'
          );
        return false;
      });
});

Without ajax form is posted as following if user pressed First button: data1=value1&button1

But when I use $.post posted form does not contain any information about button: data1=value1

jQuery 1.6.1

The behavior depends on that which button were pressed.
Any help or workaround would be appriciate!

Answer by T.J. Crowder

Since you’re stopping the browser’s default behavior, which is what supplies the button value, you’ll have to capture what button was pressed, and add that information to the data you’re posting (your serf data). Probably the most reliable way would be to hook the click event on the buttons as well as the submit event of the form, and route them all to a central function that does the ajax submission with (or without) a button value (without in the case of a form submitted another way, rather than by pressing one of those buttons).

Something along these lines:

$(document).ready(function() {
    function submitTheForm(f, button) {
        var action = f.attr("action");
        var serf = f.serialize();
        if (button && button.name) {
            serf += "&" + encodeURIComponent(button.name);
            if (button.value) {
                serf += "=" + encodeURIComponent(button.value);
            }
        }
        $.post(action, serf,
        //onreturn
          function (data) {
                //do something here on success
          },
          'json'
        );
    }
    $('#formId').submit(function () {
        submitTheForm($(this));
        return false;
    });
    $("#formId :submit").click(function() {
        submitTheForm($(this).closest('form'), this);
        return false;
    });
});

Answer by Starx

I don’t think that is suppose to be happening. But anyways, you could something like this too.

$("#formid").children("input[type="submit"]").click(function() {
    var name = $(this).attr("name");
    post(name);
    return false;
});
function post(buttnname) {
    var action = $("#formid").attr("action");
    var serf = $("#formid").serialize()+"&button="+buttname;
    $.post(action, serf,
    //onreturn
        function (data) {
            //do something here on success
          },
          'json'
        );
}
May 26, 2011

Absolute positioned image in border radius wrapper

Question by Johan Wallberg

I have a wrapper with border radius. Inside the wrapper I have a absolute positioned image in the top right corner. My problem is that the image doesn’t crop/hide under the wrapper with border radius. I’ve tried overflow:hidden on the wrapper but it doesn’t work. See image below.

enter image description here

Answer by Starx

Image tag is not affected by border-radius.

Your best bet is to use the picture as a background like:

<div id="someimage" style="background:url('image.jpg');border-radius: 5px; height: 200px; width: 500px;"></div>

The element(in above example a div) should contain the size of the actual image), and unless you use CSS3, the image cannot be resized like <img> tag

May 24, 2011

mouseover() – using addClass() with this

Question by clarkk

how can I add a class when mouse is over an element?

var row = $('<tr></tr>')
    .append('<td class="list_row">'+js2txt(string)+'</td>')
    .mouseover(function(){
        this.addClass('list_row_mover');
    });

js error:

this.addClass is not a function

Answer by KARASZI István

In your function the scope (this) is the HTML element, not the jQuery object.

Here is a possible fix:

var row = $('<tr></tr>')
  .append('<td class="list_row">'+js2txt(string)+'</td>')
  .mouseover(function(){
    $(this).addClass('list_row_mover');
  });

Answer by Starx

use

$(this).addClass("list_row_mover");

Using nl2br with html tags

Question by Alex Emilov

I use nl2br when displaying some information that is saved somewhere, but when HTML tags are used I want not to add <br> tags for them.

For example if I use

<table>
<th></th>
</table>

it will be transformed to

<table><br />
<th></th><br />
</table><br />

and that makes a lot of spaces for this table.

Ho can break line tags be added only for other non-HTML content?

Thanks.

Answer by Michiel Pater

You could replace the closing tags and newlines by only closing tags:

$str = str_replace('>
', '>', $str);

Answer by Starx

I think your question is wrong. If you are typing

<table>
<th></th>
</table>

into a text area then no matter what you do It will include <br /> in between them. Because it is what nl2br is supposed to do.

May 13, 2011

How to use jquery rewrite redirect url

Question by user610983

I created a drop down list(with javascript onchange features), I would like to rewrite the redirect url from this: http://localhost/en/abc/kk.php?CT=1 to http://localhost/abc/kk.php?lang=en&CT=1 by using jquery.

Possible to do it?

Answer by Starx

You cannot rewrite the redirect url through clientside script such as javascript itself. You need .htaccess file to do so.

However, if the urls http://localhost/en/abc/kk.php?CT=1 is already present in your markup like in anchor tags

<a href="http://localhost/en/abc/kk.php?CT=1">Some Link Text</a>

Then you can use jQuery to change the value

$(document).ready(function() {
    $("a").attr("href","http://localhost/abc/kk.php?lang=en&CT=1");
    //It is better to replace the values using pattern mathcing
});
May 11, 2011

Can't put IP-address in database

Question by Bjorn Seigers

I’m trying to put an ip-address in my database.
If I do an echo like this:

echo $_SERVER['REMOTE_ADDR'];

But if I’m trying to put it in a variable or in the database it gives nothing, so in my database it says: NULL
The commands I used for that:

$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("UPDATE users SET last_ip='".$ip."' WHERE id=".$row['id']) or die(mysql_error());

I don’t know what I’m doing wrong.
Can someone help me with this please?

Thanks!

Answer by Starx

Your code is correct and should work. Unless as commented by @wallyk, the data type of the ip field is unsupported one.

However, just to make sure wrap the WHERE condition in ' (Single Quote) and try.

jQuery select parent

Question by cabaret

This might be a duplicate question, however I did search and I got so many different answers that I don’t know which to use or how to do this.

<?
if(isset($content))
{
    $i = 1;
    foreach($content as $item)
    {
        echo "<li><a href='#' name='" . $item['id'] . "'>" . $item['title'] . "</a></li>";
        $i++;
    }
}
?>

I’ve added a function to these links with jQuery to handle an ajax call. I select the links as follows:

    $("#tips_list ul li a").click(function(e)   { //... }

However, this doesn’t make a lot of sense because now you have to click on the actual text instead of the list item. So I figured I’d re-structure my HTML so the anchor tag wraps around the li tag.

    `<a href="#" name=""><li>foo</li></a>`

I then changed my jQuery code accordingly:

    $("#tips_list ul a li").click(function(e)   { //... }

However, now, when I click.. it grabs the list item tag as $(this); which means I can’t really grab the name attribute from the anchor tag. So! What I need to do is to grab the name attribute from the parent anchor tag. And I honestly have no clue what the easiest way to do this is. I’m not that experienced with jQuery.

Thanks a lot for helping me!

Answer by phil

How about going back to the original method, and set #tips_list ul li a {display:block} in your CSS? That should make the a expand and take up the whole li, making the whole li seem clickable. Your original code should then work fine.

Answer by Starx

Keep the old markup. The later one is quite cranky and use the following script.

$("#tips_list ul li").click(function(e)   {
    var name = $(this).children("a").attr("name");
    alert(name);
}
May 6, 2011

Gap at top of page despite margin:0 and padding: 0

Question by MrB

There’s a 32px gap at the top of my site, despite setting margins and paddings to 0. I know it’s 32px because I can fix it with padding: -32px. But then I have a gap at the bottom! In Firebug, it seems the body only start 32px down from the beginning of the HTML element, even though I’ve set margins and paddings to 0.

Here’s my CSS:

html{
  height: 100%;
  padding: 0;
  margin: 0;
}

body { 
  background-color: #a7a9ac; 
  color #666666;
  background-image: url('body-bg.gif');
  background-repeat: repeat-x;
  height: 100%;
  padding: 0;
  margin: 0;
}

body, p, ol, ul, td {
  font-family: verdana, arial, helvetica, sans-serif;
  font-size:   13px;
  line-height: 18px;
}

.container_banner h1{
  font-size: 48px;
  position: relative;
  top: 130px;
  left: 250px;
  width: 400px;
}

.container_banner h3{
  position: relative;
  top: 0px;
  left: 32px;
  font-size: 10px;
  color: #F8F8F8;
}

.container_banner{
  position: relative;
  top: 0px;
  background-image: url('banner.png');
  background-repeat: no-repeat;
  margin: 0 auto;
  width: 945px;
  height: 188px;
  padding: 0px;
  background-color: #ffffff;
}

.container{
  position: relative;
  top: 0px;
  margin: 0 auto;
  min-height: 100%;
  width: 945px;
  padding: 0px;
  padding-top: 20px;
  margin-bottom: 0px;
  background-color: #ffffff;
  background-image: url('thin-background.png');
}

.content{
  margin-top: 0px;
  margin-left: 30px;
  min-height: 100%;
}

Container banner is the topmost div, followed by container (which includes content).

Thx for any help.
MrB

Answer by James

I think this is caused by the use of position: relative and your h1 element inheriting a margin by default. When you use position: relative, the margin does not seem to be shifted with the actual content and therefore gets applied to the top of the page.

I have changed the relevant CSS to fix this:

.container_banner h1{
  font-size: 48px;
  position: relative;
  top: 130px;
  left: 250px;
  width: 400px;
  margin-top: 0;
}

You may need to do the same for any other elements that are set to position: relative and have a margin (e.g. h3 tags)

It would be best to cut down on the use of position relative as it is somewhat difficult to predict such behaviour.

Answer by Starx

Or, you have an error in your CSS, color #666666. There is not : between. May be that is causing the CSS to be parsed in the wrong way.

jquery recaptcha php

Question by dave

I don’t know how can i validate the recaptcha thing via jQuery. Please help. I have the contact us form with the following fields:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>


<script type="text/javascript">

$(document).ready(function() {

$('#signup').validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
messages: {
name: {
required: 'FULL NAME Missing'
},
email: {
required: "E-MAIL ADDRESS Missing",
email: "E-MAIL ADDRESS Not Valid"
}

});



});


</script>

<form action="index.php" method="post" name="signup" id="signup">
<p>
Full Name
<br>
<input name="name" type="text" class="required" id="name" title="Type your Full Name into this box" value="<?php echo $_POST['name']; ?>">
</p>
<p>
E-Mail Address
<br>
<input name="email" type="text" id="email" title="Type your E-Mail Address into this box" value="<?php echo $_POST['email']; ?>">


</form>

Validation with the jQuery is working, but no idea how to implement the recaptcha into this.

Answer by dave

thanks all for your comments,will get it done by simple library 🙂

http://www.white-hat-web-design.co.uk/articles/php-captcha.php

And validation by using php after submitting of the form (it was easy for me to implement in less time in php than jquery. 🙂 .

special thanks to Felix Kling :).

Dave

Answer by Starx

For those sort of validate, there is a validation method in jQuery validate plugin known as remote.

Check it here

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: "check-email.php"
    }
  }
});

In this check-email.php should return string “true” to be considered valid. and string “false” to be considered false.

May 4, 2011

how to determine which button has been clicked in jquery

Question by Kyokasuigetsu

I’m using a php loop to generate multiple button elements. How can I determine which button has been clicked by using jquery?

<script type="text/javascript">

$(function(){

    if(button.click){
        alert(button.id);
    }

});

</script>

<?php for($x=0; $x<4; $x++){ ?>
<ul id="x">
<li><input type="button" id="<?php echo $x; ?>" value="<?php echo $x; ?>"/></li>
</ul>
<?php } ?>

Answer by Starx

The most common way to identify a element is id. (Literally, id does mean "identification")

The way you want it, should be something like this.

$("input").click(function() { //This will attach the function to all the input elements
   alert($(this).attr('id')); //This will grab the id of the element and alert. Although $(this).id also work, I like this way.
});

However, generalizing the bind to all the input elements might be a bad idea. So try giving a common class to specific elements and use $(".yourclass") instead.

...

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