简体   繁体   中英

How do I set a jQuery selector in coffeescript using a variable?

Im writing a Rails app, and I have multiple forms on the same page that all have different ids. in coffee script, I'm trying to set the identifier to access the text area in each. heres a quick example of what the html looks like in the browser.

HTML

<a href="#" class="link" data-plan="1">Click here</a>
<form id="new_item_plan_1">
  <textarea id="plan_1_item_field"></textarea>
</form>

Setting the plan id and trying to access the text area

plan_id = 0
$(".link").click ->
  plan_id = $(this).data("plan")
$("#plan_"+plan_id+"_item_field").keypress ->
  ...Some code...

So I have the plan_id variable initialized first, then set it to the .link s data-plan value. But my key press event doesn't work on the textarea and I dont get an error in the console.

When I make a test link and console.log it...

plan_id = 0
$(".link").click ->
  plan_id = $(this).data("plan")
$("#test).click ->
  console.log(plan_id)

it prints the correct plan_id value in the console just fine, so I have to be doing something wrong in the textarea identifier. What am I going wrong? Thanks.

Link to jsfiddle, notice how the keypress event doesn't work https://jsfiddle.net/cfscr/175/

<a href="#" class="link" data-plan="1">Click here</a>
<form id="new_item_plan_1">
  <textarea id="plan_1_item_field" class='item-field' data-plan='1'></textarea>
</form>

plan_id = 0
$(".link").click ->
  plan_id = $(this).data("plan")
$(".item-field").keypress ->
  if $(this).data('plan') == plan_id {
     ...Some code...

you could use a regex instead of another data tag in the text area, i'm just lazy ;)

Whats happening in your code is that the keypress binding is applied on page load, so its only applied once while plan id is still 0. it doesnt get re-applied when plan_id is updated.

I should note this seems like an odd thing to be doing, but you need to put the binding inside of the click event. that is, you want

$("#plan_"+plan_id+"_item_field").keypress ->
  ...Some code...

to be applied each time the click event is fired. to do so, it must be indented properly

plan_id = 0
$(".link").one 'click', ->
  plan_id = $(this).data("plan")
  $("#plan_"+plan_id+"_item_field").keypress ->
    ...Some code...

this will make is so that when the user clicks the button any number of times, it will apply the binding to that keypress. Is this what youre trying to accomplish?

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