When I try to access a javascript variable in ruby it showing an undefined variable error.
I tried to access the variable x in the ruby code "phone#{x}"
var x = 1;
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++;
$(wrapper).append('<div class="sampleclass"><%= f.label :"phone#{x}", class: "control-label col-md-3" %><div class="col-md-8"><%= f.text_field :"phone#{x}", class: "form-control" %><a href="#" class="remove_field">Remove</a></div></div>'); //add input box
}
});
I expect the output phone#{x} to phone2
-
Ruby happens on the server and javascript on the client. You need AJAX to communicate between them.Kokodoko– Kokodoko2019年07月15日 08:20:11 +00:00Commented Jul 15, 2019 at 8:20
-
In append you passing a string, so use "phone"+x+"[...rest of string]".Ritesh katare– Ritesh katare2019年07月15日 08:26:06 +00:00Commented Jul 15, 2019 at 8:26
2 Answers 2
Your expectations are completely wrong - Ruby (ERB) is executed on the server while this javascript is executed later on the client.
There is no way that you can read a javascript variable on the fly in a javascript erb template. Its just an advanced version of string interpolation, which renders javascript just the same way as it does HTML. It does not actually execute the resulting code.
A better alternative is just to use ERB to produce a template string and modify the elements with javascript.
var x = 1;
$(add_button).click(function(e){ //on add input button click
var $template = $('<div class="sampleclass"><%= f.label :phone", class: "control-label col-md-3" %><div class="col-md-8"><%= f.text_field :phone, class: "form-control" %><a href="#" class="remove_field">Remove</a></div></div>');
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++;
$template.find('label').text("phone " + x);
$template.find('input').attr(name: "phone_" + x);
$(wrapper).append(template); //add input box
}
});
Comments
You can not use rails tags inside the *.js file unless it is something like *.js.erb
I can figure out what you are trying to accomplish here. You have to use the HTML to make the whole element on the go.
You can use something like this.
$(wrapper).append('<div class="sampleclass"><label class="control-label col-md-3"> Phone'+ x +' </label><div class="col-md-8"><input type=text name="phone'+ x +'" class="form-control"><a href="#" class="remove_field">Remove</a></div></div>');
Adding a sample of how it would look with your code.