Edvards Krickis Edvards Krickis - 10 months ago 73
jQuery Question

How to change text direction of textbox on radio button click?

I have this small piece of code and can't resolve problem of direction. I have text field with constant direction of left. I have 2 radio buttons Right and Left. When i click Right it shows value of Right radio button and same with Left. I want to have that when i click Right the text shows on right side of text field

and when Left clicked

Here is code

<!doctype html>
<html lang="en">
.toggler { height: 50px; position: absolute;}
.toggler2 { position: absolute;}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
$( function() {

$('input[name="radio-1"]').on('change', function() {

} );

<legend>Choose direction: </legend>
<input type="radio" class="click" name="radio-1" id="radio-1" value="Right">
<label for="radio-1">Right</label>
<input type="radio" class="click" name="radio-1" id="radio-2" value="Left">
<label for="radio-2">Left</label>

<div class="toggler2">
<input type="text" name="direction">

Working code: https://jsfiddle.net/pk0vnkLn/

Answer Source

You can solve this by setting the dir attribute on the element based on the checked option:

$('input[name="radio-1"]').on('change', function() {
    var value = $(this).val();
    $('input[name="direction"]').val(value).attr('dir', value == 'Right' ? 'rtl' : 'ltr');

Updated fiddle