How to send object by radiobutton?

1

I have a radiobutton:

<input type='radio' onclick='clickRadioButton(this)' value='new object { nome = #: nome #}' />

It is returning a string, but I want an object with the name property.

    
asked by anonymous 27.04.2015 / 14:42

2 answers

2

I would do so

<input id="but" type="radio" value='{"nome":"um nome","sobrenome":"um sobrenome"}'>

and javascript

var radio = document.getElementById("but");
radio.addEventListener('click', function(){
    var _obj = JSON.parse(this.value);
    console.log(_obj);
});

The output on the console would be:

Object { nome: "um nome", sobrenome: "um sobrenome" }

[OTHER WAY TO DO]

Well, if your need is this, there is a better and safer way than I usually use that are data-attributes.

See the example below. I used the jQuery library to facilitate access to the elements of the page, but you can use the library you want or pure JavaScript, whatever, it will only change the way it refers to the elements:

<input type="radio" name="rd" id="rd-1" data-id="1" data-nome="um nome" data-sobrenome="um sobrenome">
<label for="rd-1">Radio 1</label><br>

<input type="radio" name="rd" id="rd-2" data-id="2" data-nome="um nome" data-sobrenome="um sobrenome">
<label for="rd-2">Radio 2</label><br>

<input type="radio" name="rd" id="rd-3" data-id="3" data-nome="um nome" data-sobrenome="um sobrenome">
<label for="rd-3">Radio 3</label><br>

<input type="radio" name="rd" id="rd-4" data-id="4" data-nome="um nome" data-sobrenome="um sobrenome">
<label for="rd-4">Radio 4</label><br>

<input type="radio" name="rd" id="rd-5" data-id="5" data-nome="um nome" data-sobrenome="um sobrenome">
<label for="rd-5">Radio 5</label><br>

and javaScript:

$("input[name=rd]").click(function(){  
    // usando data-attributes
    var _obj = {id: $(this).attr('data-id'), nome: $(this).attr('data-nome'), sobrenome: $(this).attr('data-sobrenome')};
    console.log(_obj);
});

See the example working here: link

    
27.04.2015 / 15:02
0

Instead of using this object's creation in input value, why do not you use a function that creates a new object?

function makeObj() {
    var obj = {
        nome: #
    };
    return obj;
}

<input type='radio' onclick='clickRadioButton(makeObj())' value='' />
If the idea is to parameterize the creation of this object in some way based on the input, you can still send the this.value to the makeObj method and make the object creation logic in there. Example:

function makeObj(nomeP) {
    var obj = {
        nome: nomeP
    };
    return obj;
}

<input type='radio' onclick='clickRadioButton(makeObj(this.value))' value='teste' />

Source: SOen: JavaScript: function returning an object

    
27.04.2015 / 14:46