简体   繁体   中英

How to get value from form field and concatenate with url in Jquery

I am using jquery for the first time today and need help with this problem. For the all the pros out there, this issue might sound dumb but I am struggling.

I have a form field in a HTML page, and want to get value from the form field and concatenate with a url.

<form id="form-container" class="form-container">
        <label for="street">Street: </label><input type="text" id="street" value="">
        <label for="city">City: </label><input type="text" id="city" value="">
        <button id="submit-btn">Submit</button>
    </form>

This is tag where I am want to add the values of street and city.

<img class="bgimg" src="https://maps.googleapis.com/maps/api/streetview?size=600x300&location=White House, Washington DC&key=API_KEY">
</body>

Basically the location field in this src will come from the form field. so something like this:

<img class="bgimg" src="https://maps.googleapis.com/maps/api/streetview?size=600x300&location=" + $('#street').val() + "," + $('#city').val()&key=API_KEY">
    </body>

But unfortunately this is not working and need some pointers to resolve this.

UPDATE : I am trying this method to achieve this but not working

$body.append('<img class="bgimg" src="https://maps.googleapis.com/maps/api/streetview?size=600x300&location=" + $('#street').val() + " " + $('#city').val() + "&key=ABC">'

You should modify the src of your image on form submit. Possible duplicate of this thread (you will find a detailed answer there): Changing the image source using jQuery

So something like:

function setSrc(){
$('.bgimg').prop('src','https://maps.googleapis.com/maps/api/streetview?size=600x300&location=' + $('#street').val() + ',' + $('#city').val() + '&key=API_KEY');
}

<form id="form-container" class="form-container" onSubmit="setSrc();">

如果你需要使用jQuery,那么设置img标签的'src'属性的值如下:

$('.bgimg').prop('src', '"https://maps.googleapis.com/maps/api/streetview?size=600x300&location=' + $('#street').val() + ',' + $('#city').val() + '&key=API_KEY')

You can do something like this:

var url = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location={street},{city}&key=API_KEY";

$("#submit-btn").on('click', function() {
  var street = $('#street').val();
  var city = $('#city').val();
  var finalURL = url.replace('{street}', street).replace('{city}', city);
  $('.bgimg').attr('src',finalURL);
});

Note that you shouldn't have src attribute set in the HTML , else browser will fire a request to invalid source.

Also make sure to validate the user inputs and that you've jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM