Невозможно получить значение атрибута в jquery с помощью функции val - PullRequest
0 голосов
/ 30 января 2020

Я использую текстовое поле для передачи значения. Это значение передается на кнопке HTML. Я хочу, чтобы это значение кнопки находилось внутри переменной jQuery. Проблема в том, что я просто хочу значение кнопки, которое передается jQuery.

$(document).ready(function() {
  $('#myvaluefirst').on('change', function(e) {
    $('#display_here').html($(this).val());
  })
});

function getval() {
  alert($('#display_here').val());
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<input type="text" name="myvaluefirst" id="myvaluefirst">
<button type="button" id="display_here" name="display_here" onclick="getval();">value will display here</button>

Ответы [ 5 ]

0 голосов
/ 30 января 2020

В jQuery val() используется для value атрибутов, в вашем коде вы используете элемент button, вам следует вызвать метод text(), кнопки не имеют value атрибутов

$(document).ready(function() {
  $('#myvaluefirst').on('change', function(e) {
    $('#display_here').html($(this).val());
  })
});

function getval() {
  // alert($('#display_here').val()); // Edit this as below
  alert($('#display_here').text());
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<input type="text" name="myvaluefirst" id="myvaluefirst">
<button type="button" id="display_here" name="display_here" onclick="getval();">value will display here</button>
0 голосов
/ 30 января 2020

Во-первых, не используйте встроенные обработчики событий. Поскольку вы уже включили jQuery на странице, используйте его для привязки ненавязчивого обработчика событий к кнопке.

Во-вторых, проблема заключается в том, что вы смотрите на value кнопки, все же вы устанавливаете его содержание. Используйте text() вместо val().

Также обратите внимание, что я изменил событие change на input, чтобы значение кнопки обновлялось немедленно. При использовании change значение не обновляется до тех пор, пока текстовое поле не потеряет фокус, что может вызвать перемещение кнопки, и пользователь может пропустить щелчок. Попробуйте это:

$(document).ready(function() {
  var $button = $('#display_here').on('click', function() {
    console.log($(this).text());
  });

  $('#myvaluefirst').on('input', function(e) {
    $button.text($(this).val());
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<input type="text" name="myvaluefirst" id="myvaluefirst">
<button type="button" id="display_here" name="display_here">value will display here</button>
0 голосов
/ 30 января 2020

Вы можете использовать текст или html свойство.

$(document).ready(function() {
  $('#myvaluefirst').on('change', function(e) {
    $('#display_here').html($(this).val());
  })
});

function getval() {
  alert($('#display_here').text());
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<input type="text" name="myvaluefirst" id="myvaluefirst">
<button type="button" id="display_here" name="display_here" onclick="getval();">value will display here</button>
0 голосов
/ 30 января 2020

$(document).ready(function() {
  $('#myvaluefirst').on('change', function(e) {
    $('#display_here').html($(this).val());
    $('#display_here').val($(this).val());
  })
});

function getval() {
  alert($('#display_here').val()); 
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<input type="text" name="myvaluefirst" id="myvaluefirst">
<button type="button" id="display_here" name="display_here" onclick="getval();">value will display here</button>
0 голосов
/ 30 января 2020

Надеюсь, это на самом деле вам нужно

$(document).ready(function(){
	var result;
  $('#display_here').on('click', function (e) {
	  
	  result = $('#myvaluefirst').val();
    alert(result);

  })
	
});
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Welcome</title>
	<link rel="stylesheet" href="">
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<input type="text" name="myvaluefirst" id="myvaluefirst">
	<button type="button" id="display_here" name="display_here" >value will display here</button>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...