Temple
Temple

Reputation: 199

How to switch text from two different inputs on button click?

I am trying to take the input of two different text boxes, and swap the text on a button click

Sadly, nothing is happening. Am I missing something super simple?

<input type="text" id="string1" class="str_1 inputs" value="type something pointless"/>
<input type="button" onClick="switchITup();" id="theButton" value="do something amazing">
<input type="text" id="string2" class="str_2 inputs" value="type something meaningful"/>  

function switchITup(){
var val1 = $('#string1').val;  
var val2 = $('#string2').val;     

$('#string1').text(val2);     
$('#string2').text(val1);    

$('#string1').removeClass('inputs');
$('#string1').addClass('YooHoo');    

};

Codepen here.

Upvotes: 0

Views: 141

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

In your code (val need to be val() and text() need to be val()):-

function switchITup(){
  var val1 = $('#string1').val();  
  var val2 = $('#string2').val();     

  $('#string1').val(val2);     
  $('#string2').val(val1);    

  $('#string1').removeClass('inputs');
  $('#string1').addClass('YooHoo');    
};
.inputs{
font-size:20px;
}

.YooHoo{
font-size:12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="string1" class="str_1 inputs" value="type something pointless"/>

<input type="button" onClick="switchITup();" id="theButton" value="do something amazing">

<input type="text" id="string2" class="str_2 inputs" value="type something meaningful"/>

Note:- added some style to show you that it worked fine

Upvotes: 2

Nihal
Nihal

Reputation: 5334

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("input:text").val("new value");
    });
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user"></p>

<button>Set the value of the input field</button>

</body>
</html>

Upvotes: 0

Luple
Luple

Reputation: 491

I believe it should be .val() instead of .val

Upvotes: 1

Related Questions