简体   繁体   English

单击按钮时如何编写js函数以获取输入值

[英]how to write js function to get input value when click button

i have several class="items" that include input and button, and i want to click button and identify whether siblings input has value or not.我有几个 class="items" 包括输入和按钮,我想单击按钮并确定兄弟输入是否有价值。

 function onClick(elem) { var $this = elem.tagName; var val = $this.siblings('input[type=text]').val(); if (val == '') { console.log('no input'); } else { console.log(val); } }
 <div class="items"> <input type="" name="" id="keywordSearch1" placeholder=""> <button onclick="onClick()">button1</button> </div> <div class="items"> <input type="" name="" id="keywordSearch2" placeholder=""> <button onclick="onClick()">button2</button> </div> <div class="items"> <input type="" name="" id="keywordSearch3" placeholder=""> <button onclick="onClick()">button3</button> </div>

Pass object this to the function and get the previous element with previousElementSibling from that element.将对象this传递给函数,并从该元素中使用previousElementSibling获取前previousElementSibling元素。

Please Note: val() is jQuery method, the equivalent JavaScript property is value请注意: val()是 jQuery 方法,等效的 JavaScript 属性是value

 function onClick($this) { var val = $this.previousElementSibling.value; if(val == ''){ console.log('no input'); }else{ console.log(val); } }
 <div class="items"> <input type="" name="" id="keywordSearch1" placeholder=""> <button onclick="onClick(this)">Search 1</button> </div> <div class="items"> <input type="" name="" id="keywordSearch2" placeholder=""> <button onclick="onClick(this)">Search 3</button> </div> <div class="items"> <input type="" name="" id="keywordSearch3" placeholder=""> <button onclick="onClick(this)">Search 3</button> </div>

You can pass the id of input tag from onClick function.您可以从 onClick 函数传递输入标签的 id。

function onClick(elem) {
  var $this = $(elem);
  var val = $this.val();
  if (val == '') {
    console.log('no input');
  } else {
    console.log(val);
  }
}

<div class="items">
  <input type="" name="" id="keywordSearch1" placeholder="">
  <button onclick="onClick('#keywordSearch1')">button1</button>
</div>
<div class="items">
  <input type="" name="" id="keywordSearch2" placeholder="">
  <button onclick="onClick('#keywordSearch2')">button2</button>
</div>
<div class="items">
  <input type="" name="" id="keywordSearch3" placeholder="">
  <button onclick="onClick('#keywordSearch3')">button3</button>
</div>

You have two problems:你有两个问题:

First of all, your onClick function has a elem parameter, but you never pass it in. To do that, you need to use onclick="onClick(this)" in the HTML, that way when the onClick function is called, you would get the current element as the argument.首先,你的onClick函数有一个elem参数,但你从来没有传入它。为此,你需要在 HTML 中使用onclick="onClick(this)" ,这样当onClick函数被调用时,你会获取当前元素作为参数。

 function onClick(elem) { var $this = elem.tagName; console.log(elem); }
 <div class="items"> <input type="" name="" id="keywordSearch1" placeholder=""> <button onclick="onClick(this)">button1</button> </div>

Second problem is that you are taking elem.tagName which would be a string and treating it as if it's a jQuery object.第二个问题是您正在使用elem.tagName这将是一个字符串并将其视为一个 jQuery 对象。

You should either include jQuery and use that as appropriate.您应该包含 jQuery 并根据需要使用它。 You also need to specify type="text" in order to use the input[type=text] selector:您还需要指定type="text"才能使用input[type=text]选择器:

 function onClick(elem) { var $this = $(elem); //< -- wrap the element in a jQuery wrapper var val = $this.siblings('input[type=text]').val(); if (val == '') { console.log('no input'); } else { console.log(val); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="items"> <input type="text" name="" id="keywordSearch1" placeholder=""> <button onclick="onClick(this)">button1</button> </div>

Alternatively, you can do the same without jQuery using pure JavaScript with minor changes to get the same effect:或者,您可以在不使用 jQuery 的情况下使用纯 JavaScript 进行相同的操作,只需稍作更改即可获得相同的效果:

 function onClick(elem) { //get the parent var parent = elem.parentNode; var val = parent .querySelector('input[type=text]')//search the parent's children to simulate sibling searching .value; //the non-jQuery way to get the value if (val == '') { console.log('no input'); } else { console.log(val); } }
 <div class="items"> <input type="text" name="" id="keywordSearch1" placeholder=""> <button onclick="onClick(this)">button1</button> </div>

Finally, having an in-line onclick specified in HTML is generally a bad idea.最后,在 HTML 中指定onclick通常是个坏主意。 The preferred way is to attach event listeners via JS.首选方法是通过 JS 附加事件侦听器。 In jQuery, you can do that using .on :在 jQuery 中,你可以使用.on来做到这.on

 function onClick(elem) { var $this = $(elem); var val = $this.siblings('input[type=text]').val(); if (val == '') { console.log('no input'); } else { console.log(val); } } //attach the click listerner $('button').on('click', function() { onClick(this); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="items"> <input type="text" name="" id="keywordSearch1" placeholder=""> <button>button1</button> </div> <div class="items"> <input type="text" name="" id="keywordSearch2" placeholder=""> <button>button2</button> </div> <div class="items"> <input type="text" name="" id="keywordSearch3" placeholder=""> <button>button3</button> </div>

Or in pure JavaScript:或者在纯 JavaScript 中:

 function onClick(elem) { var parent = elem.parentNode; var val = parent .querySelector('input[type=text]') .value; if (val == '') { console.log('no input'); } else { console.log(val); } } //attach the click listerner to each element var buttons = document.getElementsByTagName('button'); for(var i = 0; i < buttons.length; i++) { var button = buttons[i]; button.addEventListener("click", function() { onClick(this); }) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="items"> <input type="text" name="" id="keywordSearch1" placeholder=""> <button>button1</button> </div> <div class="items"> <input type="text" name="" id="keywordSearch2" placeholder=""> <button>button2</button> </div> <div class="items"> <input type="text" name="" id="keywordSearch3" placeholder=""> <button>button3</button> </div>

Do note, that if you are attaching the event listener directly, then you can even omit passing in this as an argument:请注意,如果您直接附加事件侦听器,那么您甚至可以省略将this作为参数传递:

  • in jQuery : $("button").on("click", onClick)在 jQuery 中: $("button").on("click", onClick)
  • in plain JS, it's a similar situation, you would do button.addEventListener("click", onClick)在普通的 JS 中,这是类似的情况,你会做button.addEventListener("click", onClick)

Once you do that, you have more options at your disposal:一旦你这样做了,你就有了更多的选择:

  • a function executed as an event listener will have the this context set as the element that it was initiated from.作为事件侦听器执行的函数会将this上下文设置为启动它的元素。 So, you can directly bind the listener所以,你可以直接绑定监听器
    • in jQuery: var $this = $(this) .在 jQuery 中: var $this = $(this)
    • in plain JS: var parent = this.parentNode在普通 JS 中: var parent = this.parentNode
  • the event listener will also be passed in the event that the listener responded to.事件侦听器也将在侦听器响应的event中传递。 From there you can find the original target that was clicked:从那里你可以找到被点击的原始目标:
function onClick(event) {
  var elem = event.target;
}

You need to make these changes to get the element values.您需要进行这些更改以获取元素值。

  1. Use previous Element Sibling, as the element is before the button.使用以前的元素兄弟,因为元素在按钮之前。
  2. Provide the current context in the onclick method onClick(this)onclick方法onClick(this)提供当前上下文
  3. You are not using the jQuery so the .siblings won't work, as this is available in the jQuery Lib您没有使用 jQuery,因此.siblings将不起作用,因为它在 jQuery Lib 中可用

 function onClick(elem) { var val = elem.previousElementSibling.value;; //var val = $this.siblings('input[type=text]').val(); if (val == '') { console.log('no input'); } else { console.log(val); } }
 <div class="items"> <input type="" name="" id="keywordSearch1" placeholder=""> <button onclick="onClick(this)">button1</button> </div> <div class="items"> <input type="" name="" id="keywordSearch2" placeholder=""> <button onclick="onClick(this)">button2</button> </div> <div class="items"> <input type="" name="" id="keywordSearch3" placeholder=""> <button onclick="onClick(this)">button3</button> </div>

First of all, I would advise your to use event-delegation instead manually add onClick to each button.首先,我建议您使用事件委托,而不是手动将 onClick 添加到每个按钮。 And also You can easily use jQuery#prev function to determine direct sibling.而且您还可以轻松地使用jQuery#prev函数来确定直接兄弟。

 $(document).on('click', '.items>button', (e) => { const siblingInputValue = $(e.target).prev().val(); debugger; console.log('Sibling input value: ' + siblingInputValue); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="items"> <input type="" name="" id="keywordSearch1" placeholder=""> <button>btn 1</button> </div> <div class="items"> <input type="" name="" id="keywordSearch2" placeholder=""> <button>btn 2</button> </div> <div class="items"> <input type="" name="" id="keywordSearch3" placeholder=""> <button>btn 3</button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM