Jump to content

How to make a string from multiple checkbox values?


giba

Recommended Posts

Hi there!

I need to get the values from multiple checkboxes and turn it into a string for sending it to an

Ajax Get Request when checking the boxes, not when sending it to the server throw submit button.

 

Because, I need to make the values of form fields available again after leaving the page without submiting the form, and coming back to that:

 

<input name"field[]" value="blue" />

<input name"field[]" value="red" />

<input name"field[]" value="green" />

 

Should be stored in a PHP Session like this "blue,red,green", for when sending to Ajax it should

be stored by PHP like.

 

S_SESSION['field[]'] = "blue,red,green";

 

To have it loaded when the page is refreshed and exploded through PHP to select each box accordingly.

 

I've also tried to concatenate the values throw a loop, but no sucess.

 

I am using jQuery and have no ideia of how to accomplishing this task in Javascript with jQuery,

I am not a newby in Javascript nor jQuery, but I don't know how to do such task.

 

Hope someone could help me!

 

Thanks in Advance!

  • 3 weeks later...

I think I din't make it very clear.

 

What I wanted was to serialize the values of checkboxes after clicking somewhere else in the page to send it to ajax GET request. After some logics I got it, but I would like to know if there is a better approach now:

 

<html>
<head>
<title>Serializing Checkbox</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(
function()
{
	$("#test").click(
	function() {
		serializeCheckbox();
	}
	);
}
);

function serializeCheckbox()
{
var string = '&string=';

var inputs = document.getElementsByTagName('input');

for( var x = 0; x < inputs.length; x++ )
{
	if(inputs[x].type == "checkbox" && inputs[x].name == 'field') 
	{
		if(inputs[x].checked == true)
		{
			string += inputs[x].value + ',';
		}
	}
}
    if (/,$/.test(string)) {
        string=string.replace(/,$/,"")
    }
alert(string);
}

</script>
</head>
<body>
<form>
<input type="button" id="test" value="Click me" />
<br />
<input name="field" type="checkbox" value="blue" />Blue<br />
<input name="field" type="checkbox" value="red" />Red<br />
<input name="field" type="checkbox" value="green" />Green<br />
</form>
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.