Reputation: 3
It confused me for a long time. I have this input field in my Partial Views:
<input name="promocode" class="field" placeholder="Arlington" id="promo_code">
And I have a main form in my layout page called "new_user" and one button signupBtn
$("#signupBtn").click(function (e) {
e.preventDefault();
var promocode = document.getElementById('promo_code').value;
...
here when I clicked the button, this promocode will fetched to promocode variable.
Here in the main form, I have a hidden field
<%= hidden_field_tag :promo_code, '' %>
I want to pass the promo_code to my controller, I write this line inside the controller:
$("#promo_code").val(promocode);
Then problem come, when I want to fetch the data in controller,
aaa = params[:promo_code]
It give me a "", I don't understand, since I checked the $("#promo_code").val( ) in view, it shows the correct data, but when I checked the controller, it is not passed; I have stacked here for a day, I know I am a new guy in ROR, but I just can't find the problem...
Upvotes: 0
Views: 177
Reputation: 102433
If I had to venture a guess then the issue is probably that you have the same id for both the inputs on the page.
Clients must return the first element in the DOM in the case of duplicate ids when you call document.getElementById
and document.querySelector
.
Thus the line $("#promo_code").val(promocode);
is really just changing the value of the first element to its own value. In other words its doing absolutely nothing.
If you instead just use the form property on the button to get the input contained in the same form as the button it will work as intented.
$(document).on('click', '#signupBtn', function(e){
this.form["promo_code"].value = $('#promo_code').val();
e.preventDefault(); // prevents a redirect for the purpose of demonstration.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="promo_code" value="foobarbaz" type="hidden" />
<form>
<input name="promo_code" value="" />
<button id="signupBtn">Copy code</button>
</form>
And as pointed out by @3limin4t0r form values are submitted using the input name, not the id. So that input would be submitted as params[:promocode]
not params[:promo_code]
.
Upvotes: 1