Как получить текст из ввода type = "text" - PullRequest
0 голосов
/ 08 сентября 2018

HTML:

<div>
 <label for="mytags">Add tags:</label>
 <input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
</div>

JS:

  this.tags = $("#mytags")
          .map(function(){return $(this).val();}).get();

Но я получаю текст от value = "1111, 2222, 3333," , а не от текста, который я печатаю в поле.

Как решить?

Это коды из API загрузчика 3 javascript Исходный код:

var UploadVideo = function() {
  /**
   * The array of tags for the new YouTube video.
   *
   * @attribute tags
   * @type Array.<string>
   * @default ['google-cors-upload']
   */
  this.tags = ['youtube-cors-upload'];
...

Может быть, у вас есть другая идея, как получить теги из ввода type = "text"?

Ответы [ 2 ]

0 голосов
/ 08 сентября 2018

Исходя из вашего последующего редактирования, похоже, что вы не просто пытаетесь получить значение поля ввода, вы пытаетесь преобразовать это значение в массив. Попытка map().get(), которую вы пытались, возвращает массив, но только массив из одного элемента (потому что вы передаете ему одно строковое значение) - похоже, вместо этого вы намереваетесь разбить эту строку на запятые:

var splitTags = function() {
  this.tags = $("#mytags")
    .val() // get the field value
    .split(/\s?,\s?/) // split on commas and (optionally) whitespace
    .filter(Boolean); // remove empty elements (caused by leading or trailing commas)
  console.log(this.tags);
  return this.tags;
}

// demo:
splitTags();
$('#mytags').on("change", splitTags);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="mytags">Add tags:</label>
  <input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
</div>
0 голосов
/ 08 сентября 2018

Примечание:

this.tags = ['youtube-cors-upload']

Примечание this.tags - это Array. Если вы перезапишите это с value из input, вместо этого оно станет String. Вы уверены, что это то, что вы хотите / нужно?

Если, однако, ваша проблема проста, как вы описываете, решение, подобное этому должно работать:

var mytags = document.getElementById('mytags');
var btn = document.getElementById('btn');
var getAttrValue = document.getElementById('getAttrValue');

btn.addEventListener('click', function() {
  // this reads whatever is currently in the input
  alert(mytags.value);
})

getAttrValue.addEventListener('click', function() {
  // this reads whatever is set in the HTML attribute value on the element
  alert(mytags.getAttribute('value'));
})
<div>
 <label for="mytags">Add tags:</label>
 <input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
 <button id="btn">Get Tags value from input</button>
 <button id="getAttrValue">Get the attribute value instead of the property value</button>
</div>

Если вам нужно проанализировать поле ввода, чтобы каждый разделенный запятыми текст становился элементом массива в this.tags, это то, что вам нужно сделать:

var tags = ['whatever-this-is'];
var tags2 = ['whatever-this-is'];
var mytags = document.getElementById('mytags');
var btn = document.getElementById('btn');

btn.addEventListener('click', function() {
  // this reads whatever is currently in the input
  // and splits the values into an array
  tags = mytags.value.replace(/ /g, '').split(',');
  // if all you want is an array with one element
  // that is whatever was in the input, do this:
  tags2 = [mytags.value];
  console.log(tags);
  console.log(tags2);
})
<div>
 <label for="mytags">Add tags:</label>
 <input name="mytags" id="mytags" type="text" value="1111, 2222, 3333,">
 <button id="btn">Get Tags value from input and put them in tags array</button>
</div>

Если ваша проблема в чем-то другом, вам нужно добавить больше информации к вашему вопросу, и я постараюсь изменить свой ответ соответствующим образом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...