Problem with window.open() JS

Asked

Viewed 664 times

0

I have a table composed of 3 columns: link, status, action.

In the action column, I have 2 links that will serve as "buttons": VIEW & DISCARD inserir a descrição da imagem aqui

This table has on average +100 lines...

I need that when the user click on VIEW, the value of the "Link" column is taken in the respective row...so that a link will be mounted where a redirection to a page will occur in a new tab.

Logical example:

String value = takes the value of the link column in the respective row
String link = "http://site"+value


What I’ve already done:

I am using the following function

<script type="text/javascript">
$(document).ready(function() {
    $('#mytable td').click(function() {
        posicao = $(this).parent().children().index(this);
        link = $('td:first', $(this).parents('tr')).text();

        $(this).attr('title', link);

        window.open("http://www.webmotors.com.br"+link);
    });
});
</script>

This function takes the value of the link column when I click on the row (tr) of the table....

The problem:

When you run window.open(site)
The page that generates in a new tab comes with a "%20" between the site and the link I have in the table value... inserir a descrição da imagem aqui

That %20 prevents you from opening the page...if I take it in hand the page opens... I don’t understand why he shows up in the middle....

The part that mounts the link is:

window.open("http://www.webmotors.com.br"+link);

I need help with that.

3 answers

3


%20 is the ASCII Encode equivalent to space, that is, a simple ' ' (ignore quotes).

Probably your link has a space at the beginning, use the method .trim() to remove unwanted spaces at the beginning and end.

Example:

window.open("http://www.webmotors.com.br"+link.trim());
  • 1

    thank you very much, the command . Trim() solved the problem, another one I learned...thanks

2

The Maicon solution is correct, but I do not think it is a good idea to "recycle" pieces of UI to use in redirects, AJAX, etc. because these kinds of problems happen that you found.

What you can do is put an extra attribute in your <tr>, something like

<tr data-link="/comprar/toyota/…">…</tr>

And then you would access the link via

var link = $(this).parents('tr').data('link');

(Consider even putting the http://www.webmotors.com.br into the data-link also; the day you want to have more than one site, you only need to tinker with one place.)

  • Thank you so much for your help, I’ll test it this way you said too...valeu

-1

use window.location.href, and puts a bar after the link, `

window.location.href("http://www.webmotors.com.br/"+link);
  • then window.location.href does not open the page in a new tab as I need...yet I put it in the code but still comes %20 and does not open properly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.