0

I have a Javascript variable which gets the value of the select box. I would like to append input field with value = the value of select box. However, could not get this to work.

$(function () {
    $(document).on("change", "#extra_crew", function (e) {
        var extra_crew = $('#extra_crew').val();
        $('#extra_crew_area').append(
                ' <div class="col-sm-12 m-t-10 m-b-10 no-padding">'
                + '<%= text_field_tag :reservation_type, "", class: "form-control m-b-10", :value => "' 
                + extra_crew 
                + '" %>'
                + '</div>');
        console.log(extra_crew);
    });
});

It works just fine but extra_crew seems a string in the input field could not concatenate.

Then it shows like this.

enter image description here

3
  • Remove the single quotes around +extra_crew+ Commented May 16, 2016 at 14:42
  • @Anand did not work, still string as +extra_crew+ Commented May 16, 2016 at 14:53
  • extra_crew_area is a div? Commented May 16, 2016 at 17:00

3 Answers 3

1

I think you might need to call html_safe on the string "'+extra_crew+'" to tell rails to render it without escaping the quotes to html entities:

+'<%= text_field_tag :reservation_type, "", class: "form-control m-b-10", :value => "'+extra_crew+'".html_safe %>'

However, I'm not sure this will work - a more conventional approach would be to create the div and then and text field entirely in javascript instead of trying to use Rails to create the input tag - something like this:

var newDiv = $("<div>", {id: "foo", class: "col-sm-12 m-t-10 m-b-10 no-padding"});
var textField = $("<input>", {type: "text", name: "reservation_type", class: "form-control m-b-1", value: extra_crew });
newDiv.append(textField);
$('#extra_crew_area').append(newDiv);

You could condense it slightly:

$('#extra_crew_area').append(
    $("<div>", {id: "foo", class: "col-sm-12 m-t-10 m-b-10 no-padding"}).append(
        $("<input>", {type: "text", name: "reservation_type", class: "form-control m-b-1", value: extra_crew })
    )
);
Sign up to request clarification or add additional context in comments.

Comments

1

Just remove '+extra_crew+' from text field and add below js

$('#extra_crew_area').find(".form-control:last input[type='text']").val(extra_crew);

Comments

0

I have test your code , it will work . but is it your server code here

<%= text_field_tag :reservation_type, "", class: "form-control m-b-10", :value => "'+extra_crew+'" %>

I think it's ruby, and it will not run on browser

1 Comment

It does not matter whether it is ruby, the problem is i get extra_crew as string instead of value probably cuz of the quotation marks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.