Search code examples
javascriptjqueryajaxformfield

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">'

Solution

  • 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.